Java OOPC - Interface

 

Interface




Interface is keyword use in Java .Instead of using ‘class’ keyword using ‘interface’ we can create interface. As the same way creating a class we can create interface also.

 

Interface is also a class, but interface is not a class it work same as a class. Difference between class and interface ,interface can not  create object because of that interface even can not create constructor, But after Java 8 we can use constructors.

 

We can not do multiple inheritance. means that we can not inherit  more than one super class from sub class.

Using extends we can not do multiple inheritance. But using the implements we can do multiple inheritance. Implements what inheritance do using the interface. So the purpose of using the interface is do the multiple inheritance.

As we know we can not create the objects to the interfaces but using the upcasting we can create objects. In here object generate side be the class indeedly, then that class is the working one. That means that class constructor is the one which invoked.

 



Point:

In Java there  is many keywords to create the class.

Class, abstract class, interface , enum class are those which can create class using.

 

 


 

Bellow code explain how interface works,

  - The `Polygon` interface declares a method called `getArea` that takes two integer parameters, `length` and `breadth`. This method is meant to calculate and display the area of a polygon.

 

   - The `Rectangle` class implements the `Polygon` interface, which means it must provide an implementation for the `getArea` method defined in the interface.

   - The `getArea` method in the `Rectangle` class calculates the area of a rectangle using the formula `length * breadth` and prints the result.

 

   - The `Main` class contains the `main` method, which serves as the entry point for the program.

   - Inside the `main` method, an instance of the `Rectangle` class (`r1`) is created.

   - The `getArea` method of the `Rectangle` class is then called with the arguments `5` and `6`.

   - As a result, the program prints "The area of the rectangle is 30" because 5 multiplied by 6 equals 30.

 

In summary, 

This program demonstrates the use of an interface (`Polygon`) to define a common method (`getArea`) that must be implemented by any class that implements the interface. The `Rectangle` class implements this interface and provides a specific implementation for calculating and displaying the area of a rectangle. The `Main` class creates an instance of the `Rectangle` class and invokes the `getArea` method to print the area of a specific rectangle.


Features: 



Comments

Popular posts from this blog

Linked List Data Structures

Java OOPC -Encapsulation