Website For Developers

Difference between Abstract Class and Interface


Class Abstract Class Interface
Class cannot contains any abstract method. There is one or more abstract method in abstract class. In interfaces, all methods are abstract.
Variables can be final, non-final, static and non-static Variables can be final, non-final, static and non-static Variables are public, static and final
Can create actual object using keyword new (can be instantiated) Cannot create actual object using keyword new (cannot be instantiated) Cannot create actual object using keyword new (cannot be instantiated)
Declares using only keyword class Declares using keyword abstract class Declares using keyword interface
Class can have constructor Abstract class can have constructor There is no constructor in interface
Does not support multiple inheritance Does not support multiple inheritance Supports multiple inheritance

Example of Class in Java

//Simple class Example without any abstraction
class Parent {
   String parentString = "Hey! Im Parent class String.";
}

class Child extends Parent {
   String childString = "Hey! This is a child class string.";

   public static void main (String [] args) {
     Child object = new Child();
     System.out.println(object.childString);
     System.out.println(object.parentString);
   }
}

Output
Hey! This is a child class string.
Hey! Im Parent class String.


Example of Abstract Class in Java

abstract class A {

  //abstract method without body
  abstract void output();
}

class B extends A {

  //abstract method implementation
  void output() {
    System.out.println( "Welcome to OnlineProgrammingHub!" );
  }
}

public class App {

  public static void main(String[] args) {
    B obj = new B();
    obj.output();
  }
}

Output
This is Abstract Class Example!

Example of Interface in Java
interface Show {
   void output(); //public and abstract by default
}

class X implements Show {
   public void output(){ //public keyword is needed
     System.out.println( "This is Java Interface Example!" );
  }
}

class InterfaceExample {
   public static void main(String[] args) {
     X obj = new X();
     obj.output();
  }
}
Output
This is Java Interface Example!

Anyway, class, abstract class and interface can create reference to object.