Let’s learn what is the difference between class and interface in java?
Difference between class and interface in java
Here’s the difference between class and interface.
Class | Interface |
“Class” keyword is used to declare class. | Whereas “interface” keyword is used to declare an interface. |
Multiple inheritance is not supported in a class | whereas interface supports multiple inheritance. |
A class can have constructor. | An interface can not have constructor. |
class can have concrete methods and abstract methods. | An interface can have only abstract methods. From Java 8 onwards an interface can have static and default methods. |
A class supports non-static, final, static and non-final variables. | An interface permits only static and final variables. |
A class can implement an interface. | An interface can extend another interface can’t implement. |
Class members can be of any type like public, private. | An interface members are only public. |
Now let’s see example on class and interface.
interface Car { public void accelerate(); } class Audi implements Car { public void accelerate() { System.out.println("Audi accelerating."); } } public class InterfaceClassExample { public static void main(String[] args) { Audi obj1 = new Audi(); obj1.accelerate(); Audi obj2 = new Audi(); obj2.accelerate(); } }
Output:
Audi accelerating.
Audi accelerating.