Abstract Classes and Interfaces

Polymorphism

🙋 Need help? Ask an expert now!

All Java objects are polymorphic. "Polymorphism" is the ability of an object to take on different forms. The most common use of polymorphism occurs when the superclass reference is used to refer to a subclass object. We touched on this concept in the chapter on inheritance. Superclasses can be used to create objects such as Superclass objectName = new SubClass();. The program below is an example of using both an abstract class and an interface.

PolymorphismExample.java
package exlcode;

public class PolymorphismExample extends PolymorphismTestOne implements PolymorphismTestTwo {

  public static void main(String[] args) {
    Object polymorphismExample = new PolymorphismExample();
    ((PolymorphismExample)polymorphismExample).print();
    ((PolymorphismExample)polymorphismExample).printGreeting();
    ((PolymorphismExample)polymorphismExample).printNumber();
  }

  // implements print method from abstract class
  public void print() {
    System.out.println("Java");
  }

  // implements printGreeting method from abstract class
  public void printGreeting() {
    System.out.println("Hello World!");
  }

  // implements printNumber method from interface
  public void printNumber() {
    System.out.println(exampleVariableOne);
  }
}
PolymorphismTestOne.java
package exlcode;

public abstract class PolymorphismTestOne {

  abstract void print();

  abstract void printGreeting();
}
PolymorphismTestTwo.java
package exlcode;

public interface PolymorphismTestTwo {

  int exampleVariableOne = 150;

  void printNumber();
}

We utilized type casts and the idea of polymorphism by creating the object polymorphismExample using Object and PolymorphismExample. We have to cast the object so that the program knows which methods we are calling. Because the PolymorphismExample class is not overriding methods from the Object class, casting is required.

For a programmer, it is essential to know about objects and when to use each type of class as we progress to higher level coding, programing, and idea developing. Look back at the topics covered thus far to ensure a strong grasp of all concepts before moving forward. It is imperative to have a strong foundation in order to build tall.

Application Question

Which of the following statements about abstract classes and interfaces is true?