Differences between Interface and class in Java


Class

A class is a blueprint from which individual objects are created. A class can contain any of the following variable types.

  • Local Variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

  • Instance Variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

  • Class Variables − Class variables are variables declared within a class, outside any method, with the static keyword.

Interfaces

An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

Along with abstract methods, an interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods.

Writing an interface is similar to writing a class. But a class describes the attributes and behaviors of an object. And an interface contains behaviors that a class implements.

Following are the important differences between Class and an Interface.

Sr. No. Key Class Interface
1 Supported Methods A class can have both an abstract as well as concrete methods. Interface can have only abstract methods. Java 8 onwards, it can have default as well as static methods.
2 Multiple Inheritance Multiple Inheritance is not supported. Interface supports Multiple Inheritance.
3 Supported Variables final, non-final, static and non-static variables supported. Only static and final variables are permitted.
4 Implementation A class can implement an interface. Interface can not implement an interface, it can extend an interface.
5 Keyword A class is declared using class keyword. Interface is declared using interface keyword.
6 Inheritance A class can inherit another class using extends keyword and implement an interface. Interface can inherit only an inteface.
7 Access A class can have any type of members like private, public. Interface can only have public members.
8 Constructor A class can have constructor methods. Interface can not have a constructor.

Example of Class vs Interface

public class JavaTester {
   public static void main(String args[]) {
      Animal tiger = new Tiger();
      tiger.eat();
      Tiger tiger1 = new Tiger();
      tiger1.eat();
   }
}
interface Animal {
   public void eat();
}
class Tiger implements Animal {
   public void eat(){
      System.out.println("Tiger eats");
   }
}

Output

Tiger eats
Tiger eats

Updated on: 07-Dec-2023

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements