Java Polymorphism and Inheritance
//Let's say we have a Hammer class:
public class Hammer {
public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}
}
/*
Its destroy method can destroy any Phone, and any other Object that extends Phone.
Here's how you might do that.
*/
public class Hammer {
public boolean destroy(Phone p) {
p.turnedOn = false;
p.price = 0;
System.out.println("BOOM");
}
public static void main(String[] args) {
Hammer h = new Hammer(); // Create new hammer object
Phone phone = new Phone(); // Create new Phone object
iPhone phone2 = new iPhone(); // Create new iPhone object
h.destroy(phone); // Destroy Phone object
h.destroy(phone2); // Destroy iPhone object (POLYMORPHISM!)
}
}
/*
The destroy method does not have to be static, because we are using an instance
of the Hammer class, named h, to call the destroy method. If we didn't want to
create a specific Hammer to destroy things, we would make the destroy method static, and call:
*/
Hammer.destroy(...);
Example of polymorphism with inheritance in Java
Ejemplo de polimorfismo y herencia en Java