Wednesday 3 January 2024

Unit 3: Inheritance and Interfaces | Java Programming | ICT. Ed 455 | BICTE | Fifth Semester | Bicte blog

 

Unit 3: 

Inheritance and interfaces

3.1 inheritance Basics

3.2 inheritance and constructors

3.3 super keyword

3.4 method overriding

3.5 polymorphism

3.6 dynamic binding

3.7 final keyword

3.8 abstract classes

3.9 access specifier

3.10 interfaces

Inheritance in Java

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

AD

The syntax of Java Inheritance

  1. class Subclass-name extends Superclass-name  
  2. {  
  3.    //methods and fields  
  4. }  

The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is called child or subclass.

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.

  1. class Employee{  
  2.  float salary=40000;  
  3. }  
  4. class Programmer extends Employee{  
  5.  int bonus=10000;  
  6.  public static void main(String args[]){  
  7.    Programmer p=new Programmer();  
  8.    System.out.println("Programmer salary is:"+p.salary);  
  9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
  10. }  
  11. }  

 Programmer salary is:40000.0

 Bonus of programmer is:10000

 

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.



Single Inheritance Example

When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class TestInheritance{  
  8. public static void main(String args[]){  
  9. Dog d=new Dog();  
  10. d.bark();  
  11. d.eat();  
  12. }}  

Output:

barking...

eating...

Multilevel Inheritance Example

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class BabyDog extends Dog{  
  8. void weep(){System.out.println("weeping...");}  
  9. }  
  10. class TestInheritance2{  
  11. public static void main(String args[]){  
  12. BabyDog d=new BabyDog();  
  13. d.weep();  
  14. d.bark();  
  15. d.eat();  
  16. }}  

Output:

weeping...

barking...

eating...

AD

Hierarchical Inheritance Example

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

AD

File: TestInheritance3.java

  1. class Animal{  
  2. void eat(){System.out.println("eating...");}  
  3. }  
  4. class Dog extends Animal{  
  5. void bark(){System.out.println("barking...");}  
  6. }  
  7. class Cat extends Animal{  
  8. void meow(){System.out.println("meowing...");}  
  9. }  
  10. class TestInheritance3{  
  11. public static void main(String args[]){  
  12. Cat c=new Cat();  
  13. c.meow();  
  14. c.eat();  
  15. //c.bark();//C.T.Error  
  16. }}  

Output:

meowing...

eating...

 

Constructors in Java

A constructor in Java is similar to a method with a few differences. Constructor has the same name as the class name. A constructor doesn't have a return type.

A Java program will automatically create a constructor if it is not already defined in the program. It is executed when an instance of the class is created.

A constructor cannot be static, abstract, final or synchronized. It cannot be overridden.

Java has two types of constructors:

  1. Default constructor
  2. Parameterized constructor

1. example of constructor in Single inheritance

In single level inheritance, the constructor of the base class is executed first.

OrderofExecution1.java

  1. /* Parent Class */  
  2. class ParentClass   
  3. {  
  4.     /* Constructor */     
  5.     ParentClass()  
  6.     {  
  7.         System.out.println("ParentClass constructor executed.");  
  8.     }  
  9. }  
  10.   
  11. /* Child Class */  
  12. class ChildClass extends ParentClass   
  13. {  
  14.     /* Constructor */  
  15.     ChildClass()  
  16.     {  
  17.         System.out.println("ChildClass constructor executed.");  
  18.     }  
  19. }  
  20.   
  21. public class OrderofExecution1  
  22. {  
  23.     /* Driver Code */  
  24.     public static void main(String ar[])   
  25.     {  
  26.         /* Create instance of ChildClass */  
  27.         System.out.println("Order of constructor execution...");  
  28.         new ChildClass();     
  29.     }  
  30. }  

Output:

Order of constructor execution...

ParentClass constructor executed.

ChildClass constructor executed.

In the above code, after creating an instance of ChildClass the ParentClass constructor is invoked first and then the ChildClass.

2. example of constructor in Multilevel inheritance

In multilevel inheritance, all the upper class constructors are executed when an instance of bottom most child class is created.

OrderofExecution2.java

  1. class College   
  2. {  
  3.     /* Constructor */  
  4.     College()  
  5.     {  
  6.         System.out.println("College constructor executed");  
  7.     }  
  8. }  
  9.   
  10. class Department extends College   
  11. {  
  12.     /* Constructor */  
  13.     Department()  
  14.     {  
  15.         System.out.println("Department constructor executed");  
  16.     }  
  17. }  
  18.   
  19. class Student extends Department   
  20. {  
  21.     /* Constructor */  
  22.     Student()  
  23.     {  
  24.     System.out.println("Student constructor executed");  
  25.     }  
  26. }  
  27. public class OrderofExecution2   
  28. {  
  29.         /* Driver Code */  
  30.     public static void main(String ar[])   
  31.     {  
  32.         /* Create instance of Student class */  
  33.         System.out.println("Order of constructor execution in Multilevel inheritance...");  
  34.         new Student();    
  35.     }  
  36. }  

Output:

Order of constructor execution in Multilevel inheritance...

College constructor executed

Department constructor executed

Student constructor executed

In the above code, an instance of Student class is created and it invokes the constructors of College, Department and Student accordingly.

3. example of same class constructor using this keyword

Here, inheritance is not implemented. But there can be multiple constructors of a single class and those constructors can be accessed using this keyword.

OrderofExecution3.java

  1. public class OrderofExecution3    
  2. {    
  3.     /* Default constructor */  
  4.     OrderofExecution3()    
  5.     {    
  6.         this("CallParam");    
  7.         System.out.println("Default constructor executed.");    
  8.     }    
  9.     /* Parameterized constructor */  
  10.     OrderofExecution3(String str)    
  11.     {    
  12.         System.out.println("Parameterized constructor executed.");  
  13.     }    
  14.     /* Driver Code */    
  15.     public static void main(String ar[])     
  16.     {     
  17.         /* Create instance of the class */  
  18.         System.out.println("Order of constructor execution...");  
  19.         OrderofExecution3 obj = new OrderofExecution3();     
  20.     }     
  21. }     

Output:

Order of constructor execution...

Parameterized constructor executed.

Default constructor executed.

In the above code, the parameterized constructor is called first even when the default constructor is called while object creation. It happens because this keyword is used as the first line of the default constructor.

AD

4. example of Calling superclass constructor using super keyword

A child class constructor or method can access the base class constructor or method using the super keyword.

OrderofExecution4.java

  1. /* Parent Class */  
  2. class ParentClass   
  3. {  
  4.     int a;  
  5.     ParentClass(int x)    
  6.     {  
  7.         a = x;  
  8.     }  
  9. }  
  10.   
  11. /* Child Class */  
  12. class ChildClass extends ParentClass      
  13. {  
  14.     int b;  
  15.     ChildClass(int x, int y)   
  16.     {  
  17.         /* Accessing ParentClass Constructor */  
  18.         super(x);  
  19.         b = y;  
  20.     }  
  21.     /* Method to show value of a and b */  
  22.     void Show()   
  23.     {  
  24.         System.out.println("Value of a : "+a+"\nValue of b : "+b);  
  25.     }  
  26. }  
  27.   
  28. public class OrderofExecution4  
  29. {  
  30.     /* Driver Code */  
  31.     public static void main(String ar[])   
  32.     {  
  33.         System.out.println("Order of constructor execution...");  
  34.         ChildClass d = new ChildClass(79, 89);  
  35.         d.Show();  
  36.     }  
  37. }  

Output:

Order of constructor execution...

Value of a : 79

Value of b : 89

In the above code, the ChildClass calls the ParentClass constructor using a super keyword that determines the order of execution of constructors.

Super Keyword in Java

The super keyword in Java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.

Usage of Java super Keyword

  1. super can be used to refer immediate parent class instance variable.
  2. super can be used to invoke immediate parent class method.
  3. super() can be used to invoke immediate parent class constructor.


super example: real use

Let's see the real use of super keyword. Here, Emp class inherits Person class so all the properties of Person will be inherited to Emp by default. To initialize all the property, we are using parent class constructor from child class. In such way, we are reusing the parent class constructor.

  1. class Person{  
  2. int id;  
  3. String name;  
  4. Person(int id,String name){  
  5. this.id=id;  
  6. this.name=name;  
  7. }  
  8. }  
  9. class Emp extends Person{  
  10. float salary;  
  11. Emp(int id,String name,float salary){  
  12. super(id,name);//reusing parent constructor  
  13. this.salary=salary;  
  14. }  
  15. void display(){System.out.println(id+" "+name+" "+salary);}  
  16. }  
  17. class TestSuper5{  
  18. public static void main(String[] args){  
  19. Emp e1=new Emp(1,"ankit",45000f);  
  20. e1.display();  
  21. }}  

Test it Now

Output:

1 ankit 45000

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

  • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass.
  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. The method must have the same name as in the parent class
  2. The method must have the same parameter as in the parent class.
  3. There must be an IS-A relationship (inheritance).


Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method are the same, and there is IS-A relationship between the classes, so there is method overriding.

  1. //Java Program to illustrate the use of Java Method Overriding  
  2. //Creating a parent class.  
  3. class Vehicle{  
  4.   //defining a method  
  5.   void run(){System.out.println("Vehicle is running");}  
  6. }  
  7. //Creating a child class  
  8. class Bike2 extends Vehicle{  
  9.   //defining the same method as in the parent class  
  10.   void run(){System.out.println("Bike is running safely");}  
  11.   
  12.   public static void main(String args[]){  
  13.   Bike2 obj = new Bike2();//creating object  
  14.   obj.run();//calling method  
  15.   }  
  16. }  

Test it Now

Output:

Bike is running safely

Polymorphism in Java

Polymorphism in Java is a concept by which we can perform a single action in different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java: compile-time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting. For example:

  1. class A{}  
  2. class B extends A{}  
  1. A a=new B();//upcasting  

For upcasting, we can use the reference variable of class type or an interface type. For Example:

  1. interface I{}  
  2. class A{}  
  3. class B extends A implements I{}  

Here, the relationship of B class would be:

B IS-A A
B IS-A I
B IS-A Object

Since Object is the root class of all classes in Java, so we can write B IS-A Object.

Example of Java Runtime Polymorphism

In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike class and overrides its run() method. We are calling the run method by the reference variable of Parent class. Since it refers to the subclass object and subclass method overrides the Parent class method, the subclass method is invoked at runtime.

Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

  1. class Bike{  
  2.   void run(){System.out.println("running");}  
  3. }  
  4. class Splendor extends Bike{  
  5.   void run(){System.out.println("running safely with 60km");}  
  6.   
  7.   public static void main(String args[]){  
  8.     Bike b = new Splendor();//upcasting  
  9.     b.run();  
  10.   }  
  11. }  

Test it Now

Output:

running safely with 60km.

Dynamic Polymorphism

Dynamic polymorphism is a process or mechanism in which a call to an overridden method is to resolve at runtime rather than compile-time. It is also known as runtime polymorphism or dynamic method dispatch. We can achieve dynamic polymorphism by using the method overriding.

In this process, an overridden method is called through a reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.

Properties of Dynamic Polymorphism

  • It decides which method is to execute at runtime.
  • It can be achieved through dynamic binding.
  • It happens between different classes.
  • It is required where a subclass object is assigned to a super-class object for dynamic polymorphism.
  • Inheritance involved in dynamic polymorphism.

AD

Method Overriding

It provides a specific implementation to a method that is already present in the parent class. it is used to achieve run-time polymorphism. Remember that, it is not possible to override the static method. Hence, we cannot override the main() method also because it is a static method.

Rules for Method Overriding

  • The name of the method must be the same as the name of the parent class method.
  • The number of parameters and the types of parameters must be the same as in the parent class.
  • There must exist an IS-A relationship (inheritance).

We call an overridden method through a reference of the parent class. The type of object decides which method is to be executed and it is decided by the JVM at runtime.

Example of Dynamic Polymorphism

In the following example, we have created two classes named Sample and Demo. The Sample class is a parent class and the Demo class is a child or derived class. The child class is overriding the dispaly() method of the parent class.

We have assigned the child class object to the parent class reference. So, in order to determine which method would be called, the type of the object would be decided by the JVM at run-time. It is the type of object that determines which version of the method would be called (not the type of reference).

Demo.java

  1. //parent class  
  2. class Sample  
  3. {  
  4. //method of the parent class  
  5. public void display()  
  6. {  
  7. System.out.println("Overridden Method");  
  8. }  
  9. }  
  10. //derived or child class  
  11. public class Demo extends Sample  
  12. {  
  13. //method of child class  
  14. public void display()  
  15. {  
  16. System.out.println("Overriding Method");  
  17. }  
  18. public static void main(String args[])  
  19. {  
  20. //assigning a child class object to parent class reference  
  21. Sample obj = new Demo();  
  22. //invoking display() method  
  23. obj.display();  
  24. }  
  25. }  

Output:

Overriding Method

Example of Method Overriding

DynamicPolymorphismExample.java

  1. public class DynamicPolymorphismExample   
  2. {  
  3. public static void main(String args[])   
  4. {  
  5. //assigning a child class object to a parent class reference   
  6. Fruits fruits = new Mango();   
  7. //invoking the method  
  8. fruits.color();                
  9. }  
  10. }  
  11. //parent class  
  12. class Fruits   
  13. {  
  14. public void color()   
  15. {  
  16. System.out.println("Parent class method is invoked.");  
  17. }  
  18. }  
  19. //derived or child class that extends the parent class  
  20. class Mango extends Fruits  
  21. {  
  22. //overrides the color() method of the parent class  
  23. @Override  
  24. public void color()   
  25. {  
  26. System.out.println("The child class method is invoked.");  
  27. }  
  28. }  

Output:

The child class method is invoked.
 

Final Keyword In Java

The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:

  1. variable
  2. method
  3. class

The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword. 

1) Java final variable

If you make any variable as final, you cannot change the value of final variable(It will be constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.

  1. class Bike9{  
  2.  final int speedlimit=90;//final variable  
  3.  void run(){  
  4.   speedlimit=400;  
  5.  }  
  6.  public static void main(String args[]){  
  7.  Bike9 obj=new  Bike9();  
  8.  obj.run();  
  9.  }  
  10. }//end of class  

Test it Now

Output:Compile Time Error

2) Java final method

If you make any method as final, you cannot override it.

Example of final method

  1. class Bike{  
  2.   final void run(){System.out.println("running");}  
  3. }  
  4.      
  5. class Honda extends Bike{  
  6.    void run(){System.out.println("running safely with 100kmph");}  
  7.      
  8.    public static void main(String args[]){  
  9.    Honda honda= new Honda();  
  10.    honda.run();  
  11.    }  
  12. }  

Test it Now

Output:Compile Time Error

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class

  1. final class Bike{}  
  2.   
  3. class Honda1 extends Bike{  
  4.   void run(){System.out.println("running safely with 100kmph");}  
  5.     
  6.   public static void main(String args[]){  
  7.   Honda1 honda= new Honda1();  
  8.   honda.run();  
  9.   }  
  10. }  

Test it Now

Output:Compile Time Error

Abstract class in Java

A class which is declared with the abstract keyword is known as an abstract class in Java. It can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.


Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the user.

Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

  1. Abstract class (0 to 100%)
  2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and non-abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember

  • An abstract class must be declared with an abstract keyword.
  • It can have abstract and non-abstract methods.
  • It cannot be instantiated.
  • It can have constructors and static methods also.
  • It can have final methods which will force the subclass not to change the body of the method.



Example of abstract class

  1. abstract class A{}  

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract method.

Example of abstract method

  1. abstract void printStatus();//no method body and abstract  

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its implementation is provided by the Honda class.

  1. abstract class Bike{  
  2.   abstract void run();  
  3. }  
  4. class Honda4 extends Bike{  
  5. void run(){System.out.println("running safely");}  
  6. public static void main(String args[]){  
  7.  Bike obj = new Honda4();  
  8.  obj.run();  
  9. }  
  10. }  

Test it Now

running safely

Access Modifiers in Java

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.

There are four types of Java access modifiers:

  1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
  2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
  3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
  4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only.


Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access Modifier

within class

within package

outside package by subclass only

outside package

Private

Y

N

N

N

Default

Y

Y

N

N

Protected

Y

Y

Y

N

Public

Y

Y

Y

Y


1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is a compile-time error.

  1. class A{  
  2. private int data=40;  
  3. private void msg(){System.out.println("Hello java");}  
  4. }  
  5.   
  6. public class Simple{  
  7.  public static void main(String args[]){  
  8.    A obj=new A();  
  9.    System.out.println(obj.data);//Compile Time Error  
  10.    obj.msg();//Compile Time Error  
  11.    }  
  12. }  

Role of Private Constructor

If you make any class constructor private, you cannot create the instance of that class from outside the class. For example:

  1. class A{  
  2. private A(){}//private constructor  
  3. void msg(){System.out.println("Hello java");}  
  4. }  
  5. public class Simple{  
  6.  public static void main(String args[]){  
  7.    A obj=new A();//Compile Time Error  
  8.  }  
  9. }  

Note: A class cannot be private or protected except nested class.


2) Default

If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.

  1. //save by A.java  
  2. package pack;  
  3. class A{  
  4.   void msg(){System.out.println("Hello");}  
  5. }  
  1. //save by B.java  
  2. package mypack;  
  3. import pack.*;  
  4. class B{  
  5.   public static void main(String args[]){  
  6.    A obj = new A();//Compile Time Error  
  7.    obj.msg();//Compile Time Error  
  8.   }  
  9. }  

In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.


3) Protected

The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

AD

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.

  1. //save by A.java  
  2. package pack;  
  3. public class A{  
  4. protected void msg(){System.out.println("Hello");}  
  5. }  
  1. //save by B.java  
  2. package mypack;  
  3. import pack.*;  
  4.   
  5. class B extends A{  
  6.   public static void main(String args[]){  
  7.    B obj = new B();  
  8.    obj.msg();  
  9.   }  
  10. }  
Output:Hello

4) Public

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier

  1. //save by A.java  
  2.   
  3. package pack;  
  4. public class A{  
  5. public void msg(){System.out.println("Hello");}  
  6. }  
  1. //save by B.java  
  2.   
  3. package mypack;  
  4. import pack.*;  
  5.   
  6. class B{  
  7.   public static void main(String args[]){  
  8.    A obj = new A();  
  9.    obj.msg();  
  10.   }  
  11. }  
Output:Hello

Interface in Java

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body.

Java Interface also represents the IS-A relationship.

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

  • It is used to achieve abstraction.
  • By interface, we can support the functionality of multiple inheritance.
  • It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.

Syntax:

  1. interface <interface_name>{  
  2.       
  3.     // declare constant fields  
  4.     // declare methods that abstract   
  5.     // by default.  
  6. }  

No comments:

Post a Comment