금요일, 4월 19
Shadow

#014 Java Polymorphism

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.

  • Select File->Open Project (Ctrl+Shift+O). (Figure-1.10 below)


Figure-1.10: Open NetBeans project

  • Observe that the Open Project dialog box appears.
  • Browse down to <LAB_UNZIPPED_DIRECTORY>/javapolymorphism/samples directory.
    • If you unzipped the hands-on lab zip file, 1025_javapolymorphism.zip, under C:\ directory under Windows, the directory to which you want to browse down should be C:\javapolymorphism\samples
    • If you unzipped the 1025_javapolymorphism.zip file under $HOME directory under Solaris/Linux, the directory to which you want to browse down should be $HOME/javapolymorphism/samples
  • Select MyOnlineShop.
  • Click Open Project. (Figure-1.11 below)


Figure-1.11: Open MyOnlineShop project

  • Observe that the MyOnlineShop project node appears under Projects tab window.

2. Build and run MyOnlineShop project

  • Right click MyOnlineShop project and select Run Project.
  • Observe the result in the Output window of the IDE. (Figure-1.12 below)

 

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

(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.

  • Right click MyOnlineShop project node and select New->Java Class.
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter ChildrenBook.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated ChildrenBook.java gets displayed in the editor window.
  • Modify the IDE generated ChildrenBook.java as shown in Code-1.20 below.
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.

  • Right click MyOnlineShop project node and select New->Java Class.
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter Cartoon.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Cartoon.java gets displayed in the editor window.
  • Modify the IDE generated Cartoon.java as shown in Code-1.21 below.
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

  • Right click MyOnlineShop project and select Run Project.
  • Observe the result in the Output window of the IDE. (Figure-1.23 below)
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

Solution: The solution up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javapolymorphism/samples/MyOnlineShop-solution.  You can just open it and run it.

Summary

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

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.

  • Select File->Open Project (Ctrl+Shift+O).
  • Observe that the Open Project dialog box appears.
  • Browse down to <LAB_UNZIPPED_DIRECTORY>/javapolymorphism/samples directory.
  • Select MyOnlineShopUsingAbstractClass.
  • Click Open Project.
  • Observe that the MyOnlineShopUsingAbstractClass project node appears under Projects tab window.

2. Build and run MyOnlineShopUsingAbstractClass project

  • Right click MyOnlineShopUsingAbstractClass project and select Run Project.
  • Observe the result in the Output window of the IDE. (Figure-2.12 below)
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

(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.

  • Right click MyOnlineShop project node and select New->Java Class.
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter ChildrenBook.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated ChildrenBook.java gets displayed in the editor window.
  • Modify the IDE generated ChildrenBook.java as shown in Code-1.20 below.
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.

  • Right click MyOnlineShop project node and select New->Java Class.
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter Cartoon.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Cartoon.java gets displayed in the editor window.
  • Modify the IDE generated Cartoon.java as shown in Code-1.20 below.
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

  • Right click MyOnlineShopUsingAbstractClass project and select Run Project.
  • Observe the result in the Output window of the IDE. (Figure-2.25 below)
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

Solution: The solution up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javapolymorphism/samples/MyOnlineShopUsingAbstractClass-solution.  You can just open it and run it.

Summary

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

 

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.

  • Select File->Open Project (Ctrl+Shift+O).
  • Observe that the Open Project dialog box appears.
  • Browse down to <LAB_UNZIPPED_DIRECTORY>/javapolymorphism/samples directory.
  • Select MyOnlineShopUsingInterface.
  • Click Open Project.
  • Observe that the MyOnlineShopUsingInterface project node appears under Projects tab window.

2. Build and run MyOnlineShopUsingInterface project

  • Right click MyOnlineShopUsingInterface project and select Run Project.
  • Observe the result in the Output window of the IDE. (Figure-3.11 below)
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.

  • Right click MyOnlineShop project node and select New->Java Class.
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter BookInterface.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated BookInterface.java gets displayed in the editor window.
  • Modify the IDE generated BookInterface.java as shown in Code-3.20 below.
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.

  • Right click MyOnlineShop project node and select New->Java Class.
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter ChildrenBook.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated ChildrenBook.java gets displayed in the editor window.
  • Modify the IDE generated ChildrenBook.java as shown in Code-3.22 below.
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.

  • Right click MyOnlineShop project node and select New->Java Class.
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter Cartoon.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Cartoon.java gets displayed in the editor window.
  • Modify the IDE generated Cartoon.java as shown in Code-3.23 below.
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

  • Right click MyOnlineShopUsingInterface project and select Run Project. (Figure-3.25 below)
  • Observe the result in the Output window of the IDE.
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

Solution: The solution up to this point is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javapolymorphism/samples/MyOnlineShopUsingInterface-solution.  You can just open it and run it.

Summary

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

 

Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)

 

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

  • The task you will have to do is something similar to the MyOnlineShopUsingInterface project above.
2. Send the following files to javaprogramminghomework@sun.com with Subject as JavaIntro-javapolymorphism.
  • Zip file of the the MyOwnAutoShopUsingInterface NetBeans project.  (Someone else should be able to open and run it as a NetBeans project.)  You can use your favorite zip utility or you can use “jar” utility that comes with JDK as following.
    • cd <parent directory that contains MyOwnAutoShopUsingInterface directory> (assuming you named your project as MyOwnAutoShopUsingInterface)
    • jar cvf MyOwnAutoShopUsingInterface.zip MyOwnAutoShopUsingInterface (MyOwnAutoShopUsingInterface should contain nbproject directory)
  • Captured output screen  – name it as JavaIntro-javapolymorphism.gif orJavaIntro-javapolymorphism.jpg (or JavaIntro-javapolymorphism.<whatver graphics format>)
    • Any screen capture that shows that your program is working is good enough.  No cosmetic polishment is required.
  • If you decide to use different IDE other than NetBeans, the zip file should contain all the files that are needed for rebuilding the project – war file with necessary source files is OK.

 

 

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.