Java Polymorphism


"The Java interface feature of the Java programming language enables the flexibility and agility of Java application development.  In this hands-on lab, you are going to explore the concept of Java Interface and abstract class. Generally, the ability to appear in many forms. In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class. More specifically, it is the ability to redefine methods for derived classes. For example, given a base class shape, polymorphism enables the programmer to define different area methods for any number of derived classes, such as circles, rectangles and triangles. No matter what shape an object is, applying the area method to it will return the correct results. Polymorphism is considered to be a requirement of any true object-oriented programming language (OOPL)." Quoted from Webopedia.

In this hands-on lab, you are going to explore polymorphic behaviors in Java programs.

 


Resources


Lab Exercises


Exercise 1: Polymorphic behavior via method overriding

In this exercise, you are going build MyOnlineShop project first and then add ChildrenBook and Cartoon subclasses of the Book class.


(1.1) Build and run MyOnlineShop NetBeans project

The MyOnlineShop project is the same project that you have built and run as part of Java Inheritance hands-on lab.  Here we are going to build it again just to get a sense of how it works.

1.  Open MyOnlineShop NetBeans project. 


Figure-1.10: Open NetBeans project

Figure-1.11: Open MyOnlineShop project

2. Build and run MyOnlineShop project

Item number 0: Type = myonlineshop.TV, Regular price = 1000.0, Sale price = 800.0
Item number 1: Type = myonlineshop.TV, Regular price = 2000.0, Sale price = 1600.0
Item number 2: Type = myonlineshop.MP3Player, Regular price = 250.0, Sale price = 225.0
Item number 3: Type = myonlineshop.Book, Regular price = 34.0, Sale price = 17.0
Item number 4: Type = myonlineshop.Book, Regular price = 15.0, Sale price = 7.5
totalRegularPrice = 3299.0
totalSalePrice = 2649.5
Figure-1.12: Result



                                                                                                                        return to top of the exercise


(1.2) Add ChildrenBook and Cartoon


Suppose you want to add two subclasses of Book class and you will call them, ChildrenBook and Cartoon.

1. Write ChildrenBook.java
package myonlineshop;

public class ChildrenBook extends Book{
   
    int age; // age this book is written for
   
    /** Creates a new instance of ChildrenBook */
    public ChildrenBook(double regularPrice,
            String publisher,
            int yearPublished,
            int age) {
        super(100, "Sun press", 2002);
        this.age = age;
    }
   
    // Override this method
    public double computeSalePrice(){
        return super.getRegularPrice() * 0.3;
    }
   
}
Code-1.20: ChildrenBook.java

2. Write Cartoon.java.  The Electronics class itself  is an abstract class because it does not provide implementation of the computeSalePrice() abstract method.
package myonlineshop;

public class Cartoon extends Book {
   
    String characterName;
   
    /** Creates a new instance of Cartoon */
    public Cartoon(double regularPrice,
            String publisher,
            int yearPublished,
            String characterName) {
        super(150, "Sun press", 1978);
        this.characterName = characterName;
    }
   
    // Override this method
    public double computeSalePrice(){
        return super.getRegularPrice() * 0.4;
    }
}
Code-1.21: Cartoon.java

3. Modify Main.java as shown in Code-1.22 below.

package myonlineshop;

public class Main {
  
    public static void main(String[] args) {
      
        // Declare and create Product array of size 5
        Product[] pa = new Product[7];
      
        // Create object instances
        pa[0] = new TV(1000, "Samsung", 30);
        pa[1] = new TV(2000, "Sony", 50);
        pa[2] = new MP3Player(250, "Apple", "blue");
        pa[3] = new Book(34, "Sun press", 1992);
        pa[4] = new Book(15, "Korea press", 1986);
        pa[5] = new ChildrenBook(15, "Pee Wee press", 1987, 8);
        pa[6] = new Cartoon(14, "Pee Wee press", 1924, "Batman");
      
        // Compute total regular price and total
        // sale price.
        double totalRegularPrice = 0;
        double totalSalePrice = 0;
      
        for (int i=0; i<pa.length; i++){
          
            // Call a method of the super class to get
            // the regular price.
            totalRegularPrice += pa[i].getRegularPrice();
          
            // Since the sale price is computed differently
            // depending on the product type, overriding
            // method of the object instance of the sub-class
            // gets invoked.  This is runtime polymorphic
            // behavior.
            totalSalePrice += pa[i].computeSalePrice();
          
            System.out.println("Item number " + i +
                    ": Type = " + pa[i].getClass().getName() +
                    ", Regular price = " + pa[i].getRegularPrice() +
                    ", Sale price = " + pa[i].computeSalePrice());
        }
        System.out.println("totalRegularPrice = " + totalRegularPrice);
        System.out.println("totalSalePrice = " + totalSalePrice);
    }
  
}
Code-1.22: Main.java

4. Build and run MyOnlineShop project

Item number 0: Type = myonlineshop.TV, Regular price = 1000.0, Sale price = 800.0
Item number 1: Type = myonlineshop.TV, Regular price = 2000.0, Sale price = 1600.0
Item number 2: Type = myonlineshop.MP3Player, Regular price = 250.0, Sale price = 225.0
Item number 3: Type = myonlineshop.Book, Regular price = 34.0, Sale price = 17.0
Item number 4: Type = myonlineshop.Book, Regular price = 15.0, Sale price = 7.5
Item number 5: Type = myonlineshop.ChildrenBook, Regular price = 100.0, Sale price = 30.0
Item number 6: Type = myonlineshop.Cartoon, Regular price = 150.0, Sale price = 60.0
totalRegularPrice = 3549.0
totalSalePrice = 2739.5
Figure-1.23: Result



                                                                                                             return to top of the exercise

Summary

In this exercise, you built MyOnlineShop project and exercised the polymorphic behavior through method overriding.

                                                                                                                        return to the top

Exercise 2: Polymorphic behavior via Abstract class

In this exercise, you are going build MyOnlineShopUsingAbstractClass project first and then add ChildrenBook and Cartoon subclasses of the Book class.


(2.1) Build and run MyOnlineShop NetBeans project

The MyOnlineShopUsingAbstractClass project  is the same project that you have built and run as part of Abstract Class and Java Interface hands-on lab.  Here we are going to build it again just to get a sense of how it works.

1.  Open MyOnlineShopUsingAbstractClass NetBeans project. 

2. Build and run MyOnlineShopUsingAbstractClass project

Item number 0: Type = myonlineshop.TV, Regular price = 1000.0, Sale price = 800.0
Item number 1: Type = myonlineshop.TV, Regular price = 2000.0, Sale price = 1600.0
Item number 2: Type = myonlineshop.MP3Player, Regular price = 250.0, Sale price = 225.0
Item number 3: Type = myonlineshop.Book, Regular price = 34.0, Sale price = 17.0
Item number 4: Type = myonlineshop.Book, Regular price = 15.0, Sale price = 7.5
totalRegularPrice = 3299.0
totalSalePrice = 2649.5
Figure-2.12: Result


                                                                                                                        return to top of the exercise


(2.2) Add ChildrenBook and Cartoon

Suppose you want to add two subclasses of Book class and you will call them, ChildrenBook and Cartoon.

1. Write ChildrenBook.java

package myonlineshop;

public class ChildrenBook extends Book{
   
    int age; // age this book is written for
   
    /** Creates a new instance of ChildrenBook */
    public ChildrenBook(double regularPrice,
            String publisher,
            int yearPublished,
            int age) {
        super(100, "Sun press", 2002);
        this.age = age;
    }
   
    // Override this method
    public double computeSalePrice(){
        return super.getRegularPrice() * 0.3;
    }
   
}
Code-2.21: ChildrenBook.java

2. Write Cartoon.java
package myonlineshop;

public class Cartoon extends Book {
   
    String characterName;
   
    /** Creates a new instance of Cartoon */
    public Cartoon(double regularPrice,
            String publisher,
            int yearPublished,
            String characterName) {
        super(150, "Sun press", 1978);
        this.characterName = characterName;
    }
   
    // Override this method
    public double computeSalePrice(){
        return super.getRegularPrice() * 0.4;
    }
   
}
Code-2.21: Cartoon.java


4. Modify Main.java as shown in Code-2.24 below. 

package myonlineshop;

public class Main {
   
    public static void main(String[] args) {
       
        // Declare and create Product array of size 5
        Product[] pa = new Product[7];
       
        // Create object instances and assign them to
        // the type of Product.
        pa[0] = new TV(1000, "Samsung", 30);
        pa[1] = new TV(2000, "Sony", 50);
        pa[2] = new MP3Player(250, "Apple", "blue");
        pa[3] = new Book(34, "Sun press", 1992);
        pa[4] = new Book(15, "Korea press", 1986);
        pa[5] = new ChildrenBook(15, "Pee Wee press", 1987, 8);
        pa[6] = new Cartoon(14, "Pee Wee press", 1924, "Batman");
       
        // Compute total regular price and total
        // sale price.
        double totalRegularPrice = 0;
        double totalSalePrice = 0;
       
        for (int i=0; i<pa.length; i++){
           
            // Call a method of the super class to get
            // the regular price.
            totalRegularPrice += pa[i].getRegularPrice();
           
            // Since the sale price is computed differently
            // depending on the product type, overriding (implementation)
            // method of the object instance of the sub-class
            // gets invoked.  This is runtime polymorphic
            // behavior.
            totalSalePrice += pa[i].computeSalePrice();
           
            System.out.println("Item number " + i +
                    ": Type = " + pa[i].getClass().getName() +
                    ", Regular price = " + pa[i].getRegularPrice() +
                    ", Sale price = " + pa[i].computeSalePrice());
        }
        System.out.println("totalRegularPrice = " + totalRegularPrice);
        System.out.println("totalSalePrice = " + totalSalePrice);
    }
   
}
Code-2.24: Main.java

5. Build and run MyOnlineShopUsingAbstractClass project

Item number 0: Type = myonlineshop.TV, Regular price = 1000.0, Sale price = 800.0
Item number 1: Type = myonlineshop.TV, Regular price = 2000.0, Sale price = 1600.0
Item number 2: Type = myonlineshop.MP3Player, Regular price = 250.0, Sale price = 225.0
Item number 3: Type = myonlineshop.Book, Regular price = 34.0, Sale price = 17.0
Item number 4: Type = myonlineshop.Book, Regular price = 15.0, Sale price = 7.5
Item number 5: Type = myonlineshop.ChildrenBook, Regular price = 100.0, Sale price = 30.0
Item number 6: Type = myonlineshop.Cartoon, Regular price = 150.0, Sale price = 60.0
totalRegularPrice = 3549.0
totalSalePrice = 2739.5
Figure-2.25: Result


                                                                                                                        return to top of the exercise

Summary

In this exercise, you built MyOnlineShopUsingAbstractClass project and exercised the polymorphic behavior through implementing (or overriding) abstract methods of an abstract class.


                                                                                                                        Return to the top


Exercise 3: Polymorphic behavior via Java interface

In this exercise, you are going build MyOnlineShopUsingInterface project first and then add ChildrenBook and Cartoon subclasses of the Book class.

  1. Build and run MyOnlineUsingInterface NetBeans project
  2. Add ChildrenBook and Cartoon subclasses

(3.1) Build and run MyOnlineUsingInterface NetBeans Project


The MyOnlineShopUsingInterface project  is the same project that you have built and run as part of Abstract Class and Java Interface hands-on lab.  Here we are going to build it again just to get a sense of how it works.

1.  Open MyOnlineShopUsingInterface NetBeans project. 

2. Build and run MyOnlineShopUsingInterface project

Item number 0: Type = myonlineshop.TV, Regular price = 1000.0, Sale price = 800.0
Item number 1: Type = myonlineshop.TV, Regular price = 2000.0, Sale price = 1600.0
Item number 2: Type = myonlineshop.MP3Player, Regular price = 250.0, Sale price = 225.0
Item number 3: Type = myonlineshop.Book, Regular price = 34.0, Sale price = 17.0
Item number 4: Type = myonlineshop.Book, Regular price = 15.0, Sale price = 7.5
totalRegularPrice = 3299.0
totalSalePrice = 2649.5
Figure-3.11: Result


(3.2) Add ChildrenBook and Cartoon

Suppose you want to add two subclasses of Book class and you will call them, ChildrenBook and Cartoon.

1. Write BookInterface.java

package myonlineshopusinginterface;

public interface BookInterface extends ProductInterface { 
    public String getPublisher();
    public void setPublisher(String publisher);
    public int getYearPublished();
    public void setYearPublished(int yearPublished);
}
Code-3.20: BookInterface.java

2. Modify Book.java as shown in Code-3.21 below.

package myonlineshopusinginterface;

public class Book extends Product implements BookInterface{
   
    private String publisher;
    private int yearPublished;
   
    /** Creates a new instance of Book */
    public Book(double regularPrice,
            String publisher,
            int yearPublished) {
        super(regularPrice);
        this.publisher = publisher;
        this.yearPublished = yearPublished;
    }
   
    // Override the method
    public double computeSalePrice(){
        return super.getRegularPrice() * 0.5;
    }
   
    public String getPublisher() {
        return publisher;
    }
   
    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }
   
    public int getYearPublished() {
        return yearPublished;
    }
   
    public void setYearPublished(int yearPublished) {
        this.yearPublished = yearPublished;
    }
   
}
Code-3.21: Book.java

3. Write ChildrenBook.java

package myonlineshopusinginterface;

public class ChildrenBook extends Book{
   
    int age; // age this book is written for
   
    /** Creates a new instance of ChildrenBook */
    public ChildrenBook(double regularPrice,
            String publisher,
            int yearPublished,
            int age) {
        super(100, "Sun press", 2002);
        this.age = age;
    }
   
    // Override this method
    public double computeSalePrice(){
        return super.getRegularPrice() * 0.3;
    }
   
}
Code-3.22: ChildrenBook.java

2. Write Cartoon.java
package myonlineshopusinginterface;

public class Cartoon extends Book {
   
    String characterName;
   
    /** Creates a new instance of Cartoon */
    public Cartoon(double regularPrice,
            String publisher,
            int yearPublished,
            String characterName) {
        super(150, "Sun press", 1978);
        this.characterName = characterName;
    }
   
    // Override this method
    public double computeSalePrice(){
        return super.getRegularPrice() * 0.4;
    }
   
}
Code-3.23: Cartoon.java

4. Modify Main.java as shown in Code-3.24 below. 

package myonlineshop;

public class Main {
   
    public static void main(String[] args) {
       
        // Declare and create Product array of size 5
        Product[] pa = new Product[7];
       
        // Create object instances and assign them to
        // the type of Product.
        pa[0] = new TV(1000, "Samsung", 30);
        pa[1] = new TV(2000, "Sony", 50);
        pa[2] = new MP3Player(250, "Apple", "blue");
        pa[3] = new Book(34, "Sun press", 1992);
        pa[4] = new Book(15, "Korea press", 1986);
        pa[5] = new ChildrenBook(15, "Pee Wee press", 1987, 8);
        pa[6] = new Cartoon(14, "Pee Wee press", 1924, "Batman");
       
        // Compute total regular price and total
        // sale price.
        double totalRegularPrice = 0;
        double totalSalePrice = 0;
       
        for (int i=0; i<pa.length; i++){
           
            // Call a method of the super class to get
            // the regular price.
            totalRegularPrice += pa[i].getRegularPrice();
           
            // Since the sale price is computed differently
            // depending on the product type, overriding (implementation)
            // method of the object instance of the sub-class
            // gets invoked.  This is runtime polymorphic
            // behavior.
            totalSalePrice += pa[i].computeSalePrice();
           
            System.out.println("Item number " + i +
                    ": Type = " + pa[i].getClass().getName() +
                    ", Regular price = " + pa[i].getRegularPrice() +
                    ", Sale price = " + pa[i].computeSalePrice());
        }
        System.out.println("totalRegularPrice = " + totalRegularPrice);
        System.out.println("totalSalePrice = " + totalSalePrice);
    }
   
}
Code-3.24: Main.java

5. Build and run MyOnlineShopUsingInterface project

Item number 0: Type = myonlineshop.TV, Regular price = 1000.0, Sale price = 800.0
Item number 1: Type = myonlineshop.TV, Regular price = 2000.0, Sale price = 1600.0
Item number 2: Type = myonlineshop.MP3Player, Regular price = 250.0, Sale price = 225.0
Item number 3: Type = myonlineshop.Book, Regular price = 34.0, Sale price = 17.0
Item number 4: Type = myonlineshop.Book, Regular price = 15.0, Sale price = 7.5
Item number 5: Type = myonlineshop.ChildrenBook, Regular price = 100.0, Sale price = 30.0
Item number 6: Type = myonlineshop.Cartoon, Regular price = 150.0, Sale price = 60.0
totalRegularPrice = 3549.0
totalSalePrice = 2739.5
Figure-3.25: Result


                                                                                                                        return to top of the exercise

Summary

In this exercise, you built MyOnlineShopUsingInterface project and exercised the polymorphic behavior through implementing (or overriding) methods of an interface.



                                                                                                                        return to the top



Homework


1. The homework is to modify the MyOwnAutoShopProject you did before: Java Inheritance homework to use Java interface.  Here I am going to call the new project MyOwnAutoShopUsingInterface.