Programming |
Interface is defined as a blueprint of class. Interface has static variables and abstract methods. It can be used to achieve fully abstraction and multiple inheritance.
Program
interface Animal { int count = 10; public void sound(); public void run(); } class Dog implements Animal { public void sound() { System.out.println("Dogs barking."); } public void run() { System.out.println("Dogs running."); } } public class TestInterface { public static void main(String[] args) { Dog dog = new Dog(); dog.sound(); dog.run(); System.out.println(Dog.count); } }
Output
Dogs barking. Dogs running. 10
What is a Marker Interface?
An interface that has no data member or method is known as a marker interface. A marker interface is completely empty. They are used to provide special information/instructions to the JVM. Examples of Marker Interfaces are:
Difference between an Abstract class and Interface
Abstract Class |
Interface |
An abstract class can have both abstract and non-abstract/concrete methods |
An Interface can only have abstract methods |
An abstract class can have members with various access levels like private, protected, default etc |
An interface must have all the members as public |
Abstract class has constructer |
Interfaces don’t have a constructer |
Abstract class can have instance variable |
Interface can’t have an instance variable |
Abstract class can have variables with different types of modifier |
Interface can have variable only with public static final modifier |
An abstract class can have static methods |
Interface cannot have static methods |
You extend an abstract class |
You implement an interface |
A class can extend only one abstract class |
A class can implement multiple interfaces |
A Java abstract class should be extended using keyword extends |
Java interface should be implemented using keyword implements |
An abstract class can extend another Java class and implement multiple interfaces |
An interface can extend only interfaces |
An abstract class cannot be instantiated, but can be invoked if a main() exists |
Interfaces are 100% abstract and cannot be instantiated |