interface{ //methods }
To use an interface in your class, append the keyword "implements" after your class name followed by the interface name.
Example for Implementing Interface
class Dog implements pet
interface Pet{ public void test(); } class Dog implements Pet{ public void test(){ System.out.println("Interface Method Implemented"); } public static void main(String args[]){ Pet p=new Dog(); p.test(); } }
Interface Method Implemented
Class | Interface |
In class, you can instantiate variable and create an object. | In an interface, you can't instantiate variable and create an object. |
Class can contain concrete(with implementation) methods | The interface cannot contain concrete(with implementation) methods |
The access specifiers used with classes are private, protected and public. |
In Interface only one specifier is used- Public |
Abstract Class | Interface |
Abstract keyword is used to create an abstract class and it can be used with methods. | Interface keyword is used to create an interface but it cannot be used with methods. |
A class can extend only one abstract class. | A class can implement more than one interface. |
An abstract class can have both abstract and non-abstract methods. | An interface can have only abstract methods. |
Variables are not final by default. It may contain non-final variables. | Variables are not final by default. It may contain non-final variables. |
An abstract class can provide the implementation of an interface. | An interface cannot provide the implementation of an abstract class. |