![]() |
VOOZH | about |
In Java, classes and interfaces are used to define the structure and behavior of programs. While they might seem similar, since both can hold methods and variables, they have very different purposes.
A class can extend another class and implement an interface, while an interface can only extend another interface, not implement a class.
A class is a blueprint for creating objects. It encapsulates fields (state) and methods (behavior) that are common to all objects of that type.
0 null
Explanation: Above code defines a Student class with two instance variables, id and name, and creates an object to demonstrate default values. It shows that objects of a class can hold state and access its fields.
An interface in Java is a blueprint of a class. Interface variables are implicitly public static final. Before Java 8, interface methods were implicitly public abstract. From Java 8 onward, interfaces can also contain default and static methods, and from Java 9 onward, private methods are allowed.
Geek 10
Explanation: Above code defines an interface with a constant and an abstract method, then implements it in a class providing method behavior. It demonstrates how a class can adopt an interface and use its constants and methods.
The following table lists all the major differences between an interface and a class in Java.
Features | Class | Interface |
|---|---|---|
Keyword | The keyword used to create a class is "class". | The keyword used to create an interface is "interface". |
Instantiation | A class can be instantiated, i.e., objects of a class can be created. | An interface cannot be instantiated directly, instead, it is implemented by a class or a struct. |
Inheritance | Classes do not support multiple inheritance. | Interface supports multiple inheritance. |
Inheritance Mechanism | A class can inherit another class using the keyword extends. | A class uses implements to adopt an interface, while an interface uses extends to inherit another interface. |
Constructors | It can contain constructors. | It cannot contain constructors. |
Methods | Methods in a class can be abstract, concrete, or both. | An interface contains abstract methods by default (before Java 8) or default/static methods (from Java 8 onward). |
Access Specifiers | Variables and methods in a class can be declared using any access specifier(public, private, default, protected). | Interface variables are public static final, and methods are public by default. |
Variables | Variables in a class can be static, final, or neither. | All variables are static and final. |
Purpose | A class is a blueprint for creating objects and encapsulates data and behaviour. | An interface specifies a contract for classes to implement by focusing on capabilities rather than implementation. |