Inheritance
Basic skills
Polymorphism
Java allows us to treat an object of a subclass as an object of its superclass. In other words, a reference variable of a superclass type can point to an object of its subclass.
How polymorphism works
- Polymorphism is a feature of inheritance that lets you treat objects of different subclasses that are derived from the same superclass as if they had the type of the superclass.
- If you access a method of a superclass object and the method is overridden in the subclasses of that class, polymorphism determines which method is executed based on the object's type.
Example: If Book is a subclass of Product, you can treat a Book object as if it were a Product object.
Example: If you call the toString method of a Product object, the toString method of the Book class is executed if the object is a Book object.
Polymorphism: 3 versions of the toString method
The toString method in the Product superclass
public String toString() { return "Code: " + code + "\n" + "Description: " + description + "\n" + "Price: " + this.getFormattedPrice() + "\n"; }The toString method in the Book subclass
public String toString() { return super.toString() + "Author: " + author + "\n"; }
The toString method in the Software subclass
public String toString() { return super.toString() + "Version: " + version + "\n"; }
Polymorphism: Code that uses the overridden methods
Book b = new Book(); b.setCode("java"); b.setDescription("Murach's Beginning Java 2"); b.setPrice(49.50); b.setAuthor("Steelman"); Software s = new Software(); s.setCode("txtp"); s.setDescription("TextPad"); s.setPrice(27.00); s.setVersion("4.7.3"); Product p; p = b; System.out.println(p.toString()); // calls toString from the Book class p = s; System.out.println(p.toString()); // calls toString from the Software class