Showing posts with label Java interface. Show all posts
Showing posts with label Java interface. Show all posts

Friday, March 29, 2024

Interface Static Methods in Java

Java 8 has added support for interface default methods as well as interface static methods which is one of the important change in Java 8 along with the addition of lambda expressions and stream API. In this post we'll see how to use interface static methods in Java and what are the rules for using them


Static method in Java interface

Like static methods in a class, now we can write static method in interfaces too. Static methods in an interface can be called independently of any object just like how static methods are called in a class.

General form of calling the interface static method

Static methods in an interface are called by using the interface name preceding the method name.

InterfaceName.staticMethodName;

Java interface static method example

public interface MyInterface {
 int method1();
 // default method, providing default implementation
 default String displayGreeting(){
    return "Hello from MyInterface";
 }
 //static method
 static int getDefaultAmount(){
    return 0;
 }
}
public class MyClass{ 
  public static void main(String[] args) { 
    int num = MyInterface.getDefaultAmount();
    System.out.println("num " + num);
  } 
}

Output

num 0

In the example code interface MyInterface has one static method getDefaultAmount(). Note that MyClass is not even implementing the interface MyInterface still static method of the MyInterface can be called from MyClass using the call MyInterface.getDefaultAmount();. This is because, no implementation or reference of the interface is required to call the static method.

Interface static methods are not inherited

Static interface methods are not inherited by-

  • Implementing classes
  • Extending interfaces

Here interface B is extending mentioned interface MyInterface, but it can not access the static method of interface MyInterface.

interface B extends MyInterface{ 
  default String displayGreeting(){
    B.getDefaultAmount(); // Compiler Error 
    return "Hello from MyInterface";
  }
}

Same way even if MyClass implements MyInterface still it can not access static method of MyInterface, either by using the class name or by using the object reference.

public class MyClass implements MyInterface{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
    return 10;
  }
  //Overriding the default method of MyInterface
  public String displayGreeting(){
    return MyInterface.super.displayGreeting();
  }
 
  public static void main(String[] args) {
    MyInterface myInt = new MyClass();

    int num = MyInterface.getDefaultAmount();
    System.out.println("num " + num);
    MyClass.getDefaultAmount(); // Compiler error
    myInt.getDefaultAmount();// Compiler error
  } 
}

Hiding interface static method

Though implementing class can't provide implementation for the static methods of an interface but the implementing class can hide the interface static method in Java by providing a method with the same signature in the implementing class.

public interface MyInterface {
  int method1();
  // default method, providing default implementation
  default String displayGreeting(){
     return "Hello from MyInterface";
  }
  static int getDefaultAmount(){
     return 0;
  }
}
Implementing class
public class MyClass implements MyInterface{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
    return 10;
  }
  //Overriding the default method of MyInterface
  public String displayGreeting(){
    return MyInterface.super.displayGreeting();
  }
  // static method
  public static int getDefaultAmount(){
    return 5;
  }
 
  public static void main(String[] args) {
    MyInterface myInt = new MyClass();

    int num = MyInterface.getDefaultAmount();
    System.out.println("num - Interface " + num);
    System.out.println("num - Class " + MyClass.getDefaultAmount());  
  } 
}

Output

num - Interface 0
num - Class 5

Here getDefaultAmount() method is provided in the MyClass class also which hides the interface static method.

Advantages of Java interface static methods

  • Interface static methods can be used for providing utility methods.
  • With Interface static methods we can secure an implementation by having it in static method as implementing classes can't override them. Though we can have a method with same signature in implementing class but that will hide the method won't override it.

That's all for this topic Interface Static Methods in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Marker Interface in Java
  2. Difference Between Abstract Class And Interface in Java
  3. PermGen Space Removal in Java 8
  4. Lambda Expressions in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Functional Interface Annotation in Java
  2. Java Stream API Examples
  3. New Date And Time API in Java 8
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. How HashMap Works Internally in Java
  6. Java Abstract Class and Abstract Method
  7. Difference Between throw And throws in Java
  8. final Vs finally Vs finalize in Java

Thursday, March 28, 2024

Interface Default Methods in Java

Java 8 has added support for default methods as well as static methods to interfaces. In this post we'll talk about interface default methods in Java.


Need for interface default methods in Java

There was a problem with interfaces in Java that they were not open to extension, which means if there was a need to add new method to an interface it would have broken the existing implementations of that interface. Thus it was imperative that all the classes implementing that interface had to provide implementation for the newly added method, even if the method was not needed. Thus Java interfaces were not easy to evolve.

One example that comes to mind is Java MapReduce API for Hadoop, which was changed in 0.20.0 release to favour abstract classes over interfaces, since they are easier to evolve. Which means, a new method can be added to abstract class (with default implementation), without breaking old implementations of the class.

Default method in Java interface

Java 8 onward it is possible to add default methods (having default implementation) in Java interfaces, thus making them easier to evolve. With the addition of default method to an interface, addition of new method, even to an interface will not break the pre-existing code.

Interface default method should be used for backward compatibility. Whenever there is a need to add new methods to an existing interface, default methods can be used so that existing implementing classes don't break and not forced to provide implementation for the newly added methods.

Java Interface Default Method Example

An interface default method in Java is defined the same way a method will be defined in a class. One difference is that in interface, default method is preceded by the keyword default.

public interface MyInterface {
  int method1();
  // default method, providing default implementation
  default String displayGreeting(){
    return "Hello from MyInterface";
  }
}
public class MyClass implements MyInterface{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
    return 10;
  }
  public static void main(String[] args) {
    MyInterface myInt = new MyClass();
    System.out.println("Value " +  myInt.method1());
    // Calls the default method provided by interface itself
    System.out.println("Greeting " + myInt.displayGreeting());
  }
}

Output

Value 10
Greeting Hello from MyInterface

It can be seen that in MyInterface interface there is a default method displayGreeting() with a default implementation. Here implementing class is not overriding and providing its own implementation of the default method thus the default implementation is used.

Implementing class can provide its own implementation of a default method by overriding it. If we use the same interface and class as used above and override the displayGreeting() method to change the implementation.

public class MyClass implements MyInterface{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
    return 10;
  }
  //Overriding the default method of MyInterface
  public String displayGreeting(){
    return "Hello from MyClass";
  }
 
  public static void main(String[] args) {
    MyInterface myInt = new MyClass();
    System.out.println("Value " +  myInt.method1());
    // Calls the default method provided by interface itself
    System.out.println("Greeting " + myInt.displayGreeting());
  }
}

Output

Value 10
Greeting Hello from MyClass

It can be seen how output has changed and now the displayGreeting() method of the implementing class is used.

Interface default methods and multiple inheritance issues

With the inclusion of default methods, interfaces may have multiple inheritance issues. Though an interface can't hold state information (interface can't have instance variables), so state information can't be inherited, but behavior in form of default method may be inherited which may cause problems. Let's see it with an example-

Let's assume there are two interfaces A and B and both have default method displayGreeting(). There is a class MyClass which implements both these interfaces A and B.

Now consider the scenarios-

  • Which implementation of default method displayGreeting() will be called when MyClass is implementing both interfaces A and B and not overriding the displayGreeting() method.
  • Which implementation of displayGreeting() will be called when MyClass is implementing both interfaces A and B and overriding the displayGreeting method and providing its own implementation.
  • If interface A is inherited by interface B, what will happen in that case?

To handle these kinds of scenarios, Java defines a set of rules for resolving default method conflicts.

  • If implementing class overrides the default method and provides its own functionality for the default method then the method of the class takes priority over the interface default methods.
    For Example, if MyClass provides its own implementation of displayGreeting(), then the overridden method will be called not the default method in interface A or B.
  • When class implements both interfaces and both have the same default method, also the class is not overriding that method then the error will be thrown.
    "Duplicate default methods named displayGreeting inherited from the interfaces"
  • In case when an interface extends another interface and both have the same default method, the inheriting interface default method will take precedence. Thus, if interface B extends interface A then the default method of interface B will take precedence.

Use of Super with interface default methods

As stated above when class implements 2 interfaces and both have the same default method then the class has to provide an implementation of its own for the default method otherwise error will be thrown. From the implementing class if you want to call the default method of interface A or interface B, then you can call the default method of the specific interface using the super keyword from the overridden default method in the class.

Syntax for calling the default method of the specific interface using super is as follows-

InterfaceName.super.methodName();

For example, if you want to call the default method of interface A.

public interface A {
  int method1();
  // default method, providing default implementation
  default String displayGreeting(){
    return "Hello from interface A";
  }
}

interface B{
  // default method, providing default implementation
  default String displayGreeting(){
    return "Hello from Interface B";
  }
}
public class MyClass implements A, B{
  // provides implementation for the non-default method
  // of the interface
  @Override
  public int method1() {
     return 10;
  }
  //Overriding the default method of MyInterface
  public String displayGreeting(){
     return A.super.displayGreeting();
  }
 
  public static void main(String[] args) {
     A myInt = new MyClass();
     System.out.println("Value " +  myInt.method1());
     // Calls the default method provided by interface itself
     System.out.println("Greeting " + myInt.displayGreeting());
  }
}

Output

Value 10
Greeting Hello from interface A

It can be seen from displayGreeting() method of the class, using super, displayGreeting() method of interface A is called here.

Difference between Interface with default method and abstract class in Java

With interfaces also providing default methods the lines between the abstract class and interface blurs a bit in Java. But there are still certain differences between them.

  • Abstract class can have constructor, instance variables but interface can't have any of them.
  • interfaces with default methods also cannot hold state information.

Points to note-

  • With Java 8 interface default methods had been added in order to make interfaces easy to evolve.
  • With interface default method, classes are free to use the default method of the interface or override them to provide specific implementation.
  • With interface default methods there may be multiple inheritance issue if same default method is provided in more than one interfaces and a class is implementing those interfaces.
  • super can be used from the implementing class to invoke the interface default method. It's general form is InterfaceName.super.methodName();
  • Interface default methods don't change the basic traits of interface, interface still can't hold state information, it is still not possible to create an instance of an interface by itself.

That's all for this topic Interface Default Methods in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Interface in Java With Examples
  2. Marker Interface in Java
  3. Difference Between Abstract Class And Interface in Java
  4. Private Methods in Java Interface
  5. Core Java Basics Interview Questions

You may also like-

  1. Lambda expressions in Java 8
  2. Try-With-Resources in Java With Examples
  3. Java Stream API Examples
  4. strictfp in Java
  5. covariant return type in Java
  6. How and why to synchronize ArrayList in Java
  7. Java ReentrantLock With Examples
  8. Bean Scopes in Spring With Examples

Monday, February 27, 2023

Private Methods in Java Interface

Interfaces in Java were living the life of having public static final fields and public abstract methods till Java 7 but got a makeover with some new features added to them later namely-
  • Capability to add default methods to interface from Java 8 onward.
  • Capability to add static methods to interface from Java 8 onward.
  • Capability to add private methods to interface from Java 9 onward.

In this post we’ll see how to add private methods to a Java interface, what is the reason to include private methods to an interface.

Private methods in Java interface

Private methods in Java interfaces are defined using private modifier the same way it is done for a Java class.

private methodName(argument_List){
 ..
 ..
}

Private methods in Java interface can be both static and non-static.

Reason to include private methods to an interface in Java

Java 8 included interface default methods and interface static methods to an interface with that inclusion it became possible to write method bodies with in an interface but a new problem was observed.

Let’s say you have 2 methods and both of them share some code and you want to write that code as a separate method which can be called from both the methods. In Java 8 that method with common code could be default or static.

Here note that both default and static methods with in a Java interface are public by default meaning the method having common code would also be implicitly public. Which means any class implementing the interface can access this method too. But that method has some code which makes sense with in the interface, calling it from any other class doesn’t make sense and it is also against the encapsulation OOPS concept because access is given to some method which is not at all required.

Let’s try to understand this scenario in Java 8 with an example-

public interface TestInterface {
 default void defMethod1(){
  sharedCode();
  System.out.println("In default method 1");
 }
 
 default void defMethod2(){
  sharedCode();
  System.out.println("In default method 2");
 }
 
 default void sharedCode(){
  System.out.println("In sharedCode, invoking it on its own"
    + " doesn't make much sense");
 }
}

As you can see in the Interface there are two default methods defMethod1() and defMethod2() in the interface. Common code executed by both the methods is kept in a separate default method to avoid duplication of the code.

But the problem with this interface is that any class implementing this interface could access sharedCode() method too as all the methods were public by default till Java 8.

public class TestClass implements TestInterface {
  public static void main(String[] args) { 
   TestClass obj = new TestClass();
   obj.sharedCode();
  }
}

Output

In sharedCode, invoking it on its own doesn't make much sense

Interface private methods Java 9 onward

With the new feature of private methods in interfaces from Java 9 onward such methods (as shown in the above example) can be written as private methods which are not visible outside the interface. That way code redundancy can be avoided while keeping the access to the method restricted.

The example showed above can use private access modifier (Java 9 onward) with the sharedCode() method with in the interface to keep access to it restricted.

public interface TestInterface {
 default void defMethod1(){
  sharedCode();
  System.out.println("In default method 1");
 }
 
 default void defMethod2(){
  sharedCode();
  System.out.println("In default method 2");
 }
 
 private void sharedCode(){
  System.out.println("In sharedCode, invoking it on its own"
    + " doesn't make much sense");
 }
}

Now trying to access sharedCode() method from a class implementing this interface will result in compile time error “The method sharedCode() is undefined for the type TestClass”.

public class TestClass implements TestInterface {
  public static void main(String[] args) { 
   TestClass obj = new TestClass();
   obj.sharedCode(); // Compiler error
  }
}
Now you can invoke default method from the implementing class which in turn invokes the private method.
public class TestClass implements TestInterface {
  public static void main(String[] args) { 
   TestClass obj = new TestClass();
   obj.defMethod1();
  }
}

Output

In sharedCode, invoking it on its own doesn't make much sense
In default method 1

As you can see now private method can be accessed through methods of the interfaces only.

Rules for private methods in Java interfaces

The usage of private methods in the Java interfaces is guided by the following rules-

  1. Private methods in an interface can't be abstract they should have method body. Trying to define a private method as a regular public abstract method in an interface results in the error "This method requires a body instead of a semicolon"
  2. If you want to invoke a private method from a static method in an interface then you should write a private static method. From a static context you cannot access a non-static method it will give you an error “Cannot make a static reference to the non-static method”.
  3. A default method in an interface can invoke both static and non-static private methods with in an interface.

That's all for this topic Private Methods in Java Interface. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Marker Interface in Java
  2. Difference Between Abstract Class And Interface in Java
  3. New Date And Time API in Java With Examples
  4. PermGen Space Removal in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. How and Why to Synchronize ArrayList in Java
  2. How HashMap Internally Works in Java
  3. ConcurrentHashMap in Java With Examples
  4. String Comparison in Java equals(), compareTo(), startsWith() Methods
  5. Java Exception Handling And Method Overriding
  6. Java Program to Find First Non-Repeated Character in a Given String
  7. Bean Scopes in Spring With Examples
  8. Data Compression in Hadoop

Monday, May 23, 2022

Interface in Java With Examples

In this tutorial you will learn about Interface in Java which helps in achieving full abstraction in Java. Using interfaces you can specify what a class should do, but how class does it is not specified.


How does Interface differ from a class

Interfaces in Java looks syntactically similar to classes, but they differ in many ways-

  • Interfaces don't have instance variables, which means interfaces don't have a state.
  • In interfaces methods are declared with out any body. They end with a semicolon.
  • An interface in Java can't be instantiated, which also means that interfaces can't have constructors.
  • An interface is implemented by a class, not extended.
  • An interface itself can extend multiple interfaces.

Please note that, Java 8 onward, it is possible to add a default implementation to a method in an interface as well as interface static methods and even Private Methods in Java Interface Java 9 onward, here we'll discuss interfaces in its normal form.

General form of interface in Java

access_modifier interface name {
 type final_var1 = value;
 type final_var2 = value;
 ----
 ----
 return_type method_name1(param_list);
 return_type method_name2(param_list);
 ----
 ----
}

If no access modifier is specified, that means default access where interface is available to other members of the package in which it is declared. When interface is declared as public, it can be used by any program.

For top level interfaces only these two access modifiers (default and public) are permitted, there are nested interfaces which can be declared as public, private or protected. We'll discuss nested interfaces later in the post.

All the variables declared inside an interface in Java are implicitly public, final and static, which means they can't be changed by the implementing class. They should also be initialized.

All the methods with in an interface in Java are implicitly abstract methods and should be implemented by a class that is implementing the interface. Methods in an interface are also implicitly public.

Note that Java 9 onward you can also add private methods to a Java interface. Please refer Private Methods in Java Interface to know more about adding private methods in a Java interface.

Java Interface example

public interface MyInterface {
 int i = 10;
 Number method1();
 void method2(String Id);
}

Here is an interface MyInterface which has one variable i, which is public static final implicitly. There are 2 methods, one has no return type, one returns Number.

Implementing an Interface in Java

In Java, class uses implements keyword to implement an interface.

public class MyClass implements MyInterface { 
 public Integer method1() {
  System.out.println("in method 1" + i);  
  return null;
 }

 public void method2(String Id) {
  System.out.println("in method 2");  
 }
 public static void main(String[] args) {
  
 }
}

When implementing methods defined in interfaces there are several important points-

  • A class can implement more than one interface, in that case interfaces are separated with a comma.
     class class_name implements interface 1, interface 2{
     }
     
  • The methods of an interface that are implemented by a class must be declared public i.e. visibility can't be reduced.
  • The signature of the interface method must remain same while implementing it. In case of return type subclass of the return type as defined in interface can also be used. As in the above program method1 has the return type Number where as in the implemented method in the class has the return type Integer. It is permissible as Integer is the sub-class of Number.
  • The initialized variable in the interface is constant and it is not allowed to change that value in the implementing class. For example in the above program there is a variable i with value 10 if we try to change that value to 20 in the implementing class it will throw compiler error "The final field MyInterface.i cannot be assigned".
  • Any number of classes can implement an interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.
  • A class can extend only one class, but a class can implement many interfaces. Which means multiple inheritance is not allowed in Java
  • An interface can extend another interface, similar to the way that a class can extend another class.

Extending an interface in Java

Just like class, if an interface in Java is inheriting from another interface it uses extends keyword.
An interface, unlike class, can extend more than one interface. If a class implements an interface that inherits another interface, it must provide implementation for all the methods that are there in the inheritance chain of interface.

Extending an interface Java Example

// Interface
public interface MyInterface {
 int i = 10;
 Number method1();
 void method2(String Id);
}
// extending interface
interface B extends MyInterface{
 void method3();
}

// class implements all methods of MyInterface and B
public class MyClass implements B {
 
 public Integer method1() {
  System.out.println("in method 1" + i);  
  return null;
 }

 public void method2(String Id) {
  System.out.println("in method 2");  
 }

 public void method3() {
  System.out.println("in method 3");  
 }
 public static void main(String[] args) {
  
 }
}

It can be seen that the class Myclass has to implement all the methods in the inheritance chain of the interface.

Partial implementation of interface by a class

If a class implements an interface but does not implement all the methods of that interface then that class must be declared as abstract.

public interface MyInterface {
 void method1();
 String method2(String Id);
}
implemnting java interface methods

Compiler error that class must implement methods declared in MyInterface interface.

But we can declare the class as abstract in that case

public abstract class AbstractClassDemo implements MyInterface {
 public static void main(String[] args) {
  System.out.println();
 }
}

Nested Interfaces in Java

An interface or a class can have another interface. Such an interface is known as nested interface or a member interface in Java.
A nested interface can be declared as public, private or protected. When a nested interface is used outside, it must be used as a fully qualified name i.e. must be qualified by the name of the class or interface of which it is a member.

Java nested interface Example

// Class with nested interface
class A{
 public interface TestInterface{
  void displayValue(String value);
 }
}

// class implementing the nested interface
class B implements A.TestInterface{
 public void displayValue(String value) {
  System.out.println("Value is " + value);
 }
}

public class MyClass{ 
 public static void main(String[] args) {
  // reference of class B assigned to nested interface
  A.TestInterface obRef = new B();
  obRef.displayValue("hello");
 }
}

Output

Value is hello

Interface and run time polymorphism

As we already know that there can't be an object of an interface, but interface can be used to create object references. As run time polymorphism in Java is implemented through the use of super class reference thus interface can be used to provide super class reference which holds references of sub-classes at run time and provide the appropriate functionality.

Run time polymorphism using interface Java Example

Let's assume that in an application there is a need to handle payment done through several modes like; cash, cheque, credit card etc. and based on the mode of the payment the functionality may be different.
This can be achieved through an interface where the interface defines a method payment and then several classes implement that interface and provide the functionality for the payment method according to the business needs. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.

public interface PaymentInt {
 public void payment(double amount);
}
// Cash Payment implementation of Payment interface
class CashPayment implements PaymentInt{
 // method implementation according to cash payment functionality
 public void payment(double amount) {
  System.out.println("Cash Payment of amount " + amount);
 }
}

//Cheque Payment implementation of Payment interface
class ChequePayment implements PaymentInt{
 // method implementation according to cheque payment functionality
 public void payment(double amount) {
  System.out.println("Cheque Payment of amount " + amount);  
 }
}

//CreditCard Payment implementation of Payment interface
class CreditCardPayment implements PaymentInt{
 // method implementation according to credit card payment functionality
 public void payment(double amount) {
  System.out.println("CreditCard Payment of amount " + amount);
 }
}

public class PaymentDemo {
 public static void main(String[] args) {
  // Payment interface reference holding the CashPayment obj
  PaymentInt paymentInt = new CashPayment();
  paymentInt.payment(134.67);
  // Payment interface reference holding the CreditCardPayment obj
  paymentInt = new CreditCardPayment();
  paymentInt.payment(2347.89);
  // Payment interface reference holding the ChequePayment obj
  paymentInt = new ChequePayment();
  paymentInt.payment(1567.45);
 }
}

Output

Cash Payment of amount 134.67
CreditCard Payment of amount 2347.89
Cheque Payment of amount 1567.45

It can be seen how at run time reference is changed and the appropriate payment method is called.

Points to note-

  • Interfaces help in achieving full abstraction in Java.
  • For top level interfaces only default and public access modifiers are permitted.
  • All the variables in interface are implicitly public, static and final.
  • All the methods in an interface are implicitly public and abstract.
  • The methods of an interface that are implemented by a class must be declared public.
  • If a class implements an interface but does not implement all the methods of that interface then that class must be declared as abstract.
  • A class can extend only one class, but implement many interfaces.
  • An interface, unlike class, can extend more than one interface.
  • An interface or a class can have another interface. Such an interface is known as nested interface or a member interface.
  • Any number of classes can implement an interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.
  • With Java 8, it is possible to add a default implementation to a method in an interface.

That's all for this topic Interface in Java With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Marker Interface in Java
  2. Difference Between Abstract Class And Interface in Java
  3. Interface Default Methods in Java 8
  4. Interface Static Methods in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. Polymorphism in Java
  2. final Keyword in Java With Examples
  3. Java Abstract Class and Abstract Method
  4. covariant return type in Java
  5. Varargs (Variable-length Arguments) in Java
  6. Difference between HashMap and ConcurrentHashMap in Java
  7. How to Loop Through a Map in Java
  8. Java Lambda Expression And Variable Scope

Tuesday, August 17, 2021

Marker Interface in Java

Marker interface in Java is an interface that has no method declarations or fields in it. It is used as a tag to let the compiler know it needs to add some special behavior to the class implementing marker interface. That is why marker interface is also known as tag interface in Java.

Some of the examples of marker interface in Java are-

  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.RandomAccess

Saturday, June 26, 2021

Difference Between Abstract Class And Interface in Java

Difference between abstract class and interface in Java is one of the most popular java interview questions and many times it is a kind of "breaking the ice" question when the interview just starts. But that way Abstract class Vs Interface becomes a very important question as it is often said "first impression is the last impression" so let's try to see the differences between abstract class and interface in Java in this post.

First of all it is very important to know what an abstract class is and what an interface is. So please go through these two posts abstract class in Java and interface in Java to familiarize yourself with abstract class and interface.

There are also some similarities between abstract class and interface in Java like both can't be instantiated, both have abstract methods where extending/implementing class has to provide the implementation for such methods.

Abstract class Vs Interface in Java

Abstract Class Interface
Methods Abstract class can have both abstract methods (method with no body) and non-abstract methods (methods with implementation). Interface can have abstract methods only.
Note: From Java 8 interfaces can have default methods and static methods and private methods Java 9 onward. So on this account both abstract classes and interfaces in Java are becoming quite similar as both can have methods with implementation.
Access Modifiers Abstract class methods can have public, protected, private and default modifier apart from abstract methods. In interface methods are by default public abstract only. From Java 9 private methods can also be added to a Java interface.
Variables Abstract class fields can be non-static or non-final. In interface all the fields are by default public, static, final.
Implementation Abstract class may have some methods with implementation and some methods as abstract. In interface all the methods are by default abstract, where only method signature is provided. Note: From Java 8 interfaces can have default methods where default implementation can be provided with in the interface and static methods that can be accessed using the Interface name. Apart from that interfaces can have private methods too Java 9 onward.
Constructor Abstract classes have a constructor, it may be user supplied or default in case no constructor is written by a user. Interfaces can't have a constructor.
Multiple Inheritance Abstract class can extend at most one class and implement one or more interfaces. Interface can only extend one or more interfaces.
Extends/Implements Abstract class are extended by the sub-classes. Sub-classes need to provide implementation for all the abstract methods of the extended abstract class or be declared as abstract itself. Interface is implemented by a class and the implementing class needs to provide implementation for all the abstract methods declared in an interface. If a class does not implement all the abstract methods of an interface then that class must be declared as abstract.
Easy to evolve Abstract class was considered easy to evolve as abstract classes could add new methods and provide default implementation to those methods. Interface was not considered easy to evolve as, in the case of adding new method to an interface, all the implementing classes had to be changed to provide implementation for the new method. With Java 8 even interfaces can have default methods so that issue has been addressed.

Which one should you use, abstract classes or interfaces?

As we know abstract classes have to be extended where as interfaces need to be implemented by a class. That itself suggests when to use what, in case you need to extend some functionality further you need to go with abstract class. When you need to start from generalized structure and move towards more specialized structure by extending the generalized class and providing specialized implementations, abstract class is a better choice.

In case of interfaces it is expected that unrelated classes would implement that interface and each class is free to provide their own implementation. That's how using interfaces, Java fully utilizes "one interface, multiple methods" aspect of polymorphism.

That's all for this topic Difference Between Abstract Class And Interface in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Interface in Java With Examples
  2. Marker Interface in Java
  3. Interface Static Methods in Java 8
  4. Interface Default Methods in Java 8
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. What are JVM, JRE and JDK in Java
  2. static Keyword in Java With Examples
  3. super Keyword in Java With Examples
  4. this Keyword in Java With Example
  5. Reflection in Java - Getting Class Information
  6. Autowiring using XML configuration in Spring
  7. How HashMap Works Internally in Java
  8. Count Number of Words in a String Java Program