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

1
2
3
4
5
6
7
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on