interface keyword in java
The ” interface
” keyword is used to declare a new Java interface, which is a collection of methods and constants.
Interfaces are a powerful feature of the Java language.
Any class can implement one or more interfaces, meaning it implements all of the methods declared in those interfaces.
Example
- interface Shape{
- public double getArea();
- public void draw();
- }
interface Shape{ public double getArea(); public void draw(); }
Now any number of classes can implement this interface as we can see below that Triangle class is implementing it
- Class Triangle implements Shape{
- double base=5;
- double height=10;
- public double getArea(){
- return 0.5*base*height;
- }
- public void draw(){
- System.out.println("It's a triangle");
- }
- }
Class Triangle implements Shape{ double base=5; double height=10; public double getArea(){ return 0.5*base*height; } public void draw(){ System.out.println("It's a triangle"); } }
Note:
All the methods in the interface are public and abstract
All the constants defined in the interface are public,static and final