Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Polymorphism
Java Objects Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Objects Micro Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of understanding regarding Java objects.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
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.