This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 2, 2023

Explain interface in Java. How does interface support polymorphism?

 In Java, an interface is a collection of abstract methods and constants that can be implemented by any class. An interface is similar to a class, but it only defines the contract that a class should implement, without specifying the implementation details.


An interface is declared using the interface keyword in Java. For example:

public interface MyInterface {
  public void doSomething();
  public int getValue();
}

The interface defines two abstract methods doSomething() and getValue(), which any class that implements the MyInterface interface must implement.

One of the main benefits of using interfaces is that they support polymorphism, which allows objects of different classes to be treated as if they were of the same type. This allows for greater flexibility and code reuse in object-oriented programming.

For example, suppose we have an interface called Drawable that defines a method draw():

public interface Drawable {

  public void draw();
}

We can then create multiple classes that implement the Drawable interface, such as Rectangle, Circle, and Triangle, each of which provides its own implementation of the draw() method.

public class Rectangle implements Drawable {
  public void draw() {
    // implementation of draw method for rectangle
  }
}
public class Circle implements Drawable {
  public void draw() {
    // implementation of draw method for circle
  }
}
public class Triangle implements Drawable {
  public void draw() {
    // implementation of draw method for triangle
  }
}

Now, we can create an array of Drawable objects and call the draw() method on each of them, without knowing the specific implementation details of each class:

Drawable[] shapes = {new Rectangle(), new Circle(), new Triangle()};
for (Drawable shape : shapes) {
  shape.draw();
}

This is an example of polymorphism, where objects of different classes that implement the same interface can be treated as if they were of the same type, allowing for greater code reuse and flexibility in programming.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget