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. interface Shape{
  2.  
  3.    public double getArea();
  4.  
  5.    public void draw();
  6.  
  7. }
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. Class Triangle implements Shape{
  2.  
  3.     double base=5;
  4.  
  5.     double height=10;
  6.  
  7.     public double getArea(){
  8.  
  9.     return 0.5*base*height;
  10. }
  11.  
  12. public void draw(){
  13.     System.out.println("It's a triangle");
  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");
  }
}

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

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