금요일, 4월 19
Shadow

#013 Java Interface and Abstract Class

Lab Exercises

 

Exercise 1: Abstract class

In this exercise, you will write Java program that use abstract classes.  You will also learn how to add polymorphic behavior to the program through abstact methods.

(1.1) Build and run an application that uses an Abstract class

0. Start NetBeans IDE if you have not done so.
1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select Java under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyAbstractClassProject. (Figure-1.10 below)
  • Click Finish.

Figure-1.10: Create a project

  • Observe that the MyAbstractClassProject project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.

2. Write LivingThing.java as an abstract class.

  • Right click MyAbstractClassProject 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 LivingThing.
  • For the Package field, either enter myabstractclassproject or choose myabstractclassprojectfrom the drop-down menu.  (Figure-1.11 below)
  • Click Finish.


Figure-1.11: Write LivingThing abstract class

  • Observe that IDE generated LivingThing.java gets displayed in the editor window.
  • Modify the IDE generated LivingThing.java as shown in Code-1.12 below.
  • Study the code by paying special attention to bold-fonted part.
package myabstractclassproject;// The LivingThing class is an abstract class because
// some methods in it are declared as abstract methods.
public abstract class LivingThing {

private String name;

public LivingThing(String name){
this.name = name;
}

public void breath(){
System.out.println(“Living Thing breathing…”);
}

public void eat(){
System.out.println(“Living Thing eating…”);
}

/**
* Abstract method walk()
* We want this method to be implemented by subclasses of
* LivingThing
*/
public abstract void walk();

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

Code-1.12: LivingThing.java

3. Write Human.java.  The Human.java is a concrete class that extends the LivingThing abstract class.

  • Right click MyAbstractClassProject 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 Human.
  • For the Package field, either enter myabstractclassproject or choose myabstractclassprojectfrom the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Human.java gets displayed in the editor window.
  • Modify the IDE generated Human.java as shown in Code-1.13 below.
  • Study the code by paying special attention to bold-fonted part.
package myabstractclassproject;public class Human extends LivingThing {

public Human(String name){
super(name);
}

// Provide implementation of the abstract method.
public void walk(){
System.out.println(“Human ” + getName() + ” walks…”);
}

}

Code-1.13: Human.java

4. Write Monkey.java. (Code-1.14 below)

package myabstractclassproject;public class Monkey extends LivingThing {

public Monkey(String name){
super(name);
}

// Implement the abstract method
public void walk(){
System.out.println(“Monkey ” + getName() + ” also walks…”);
}
}

Code-1.14: Monkey.java

5.  Modify Main.java as shown in Code-1.15 below.  Study the code by paying special attention to bold-fonted part.

package myabstractclassproject;public class Main {

public static void main(String[] args) {

// Create Human object instance
// and assign it to Human type.
Human human1 = new Human(“Sang Shin”);
human1.walk();

// Create Human object instance
// and assign it to LivingThing type.
LivingThing livingthing1 = human1;
livingthing1.walk();

// Create a Monkey object instance
// and assign it to LivingThing type.
LivingThing livingthing2 = new Monkey(“MonkeyWrench”);
livingthing2.walk();

// Display data from human1 and livingthing1.
// Observe that they refer to the same object instance.
System.out.println(“human1.getName() = ” + human1.getName());
System.out.println(“livingthing1.getName() = ” + livingthing1.getName());

// Check of object instance that is referred by x and
// y is the same object instance.
boolean b1 = (human1 == livingthing1);
System.out.println(“Do human1 and livingthing1 point to the same object instance? ” + b1);

// Compile error
// LivingThing z = new LivingThing();
}

}

Code-1.15: Main.java

6. Build and run the program.

  • Right click MyAbstractClassProject and select Run.
  • Observe the result is displayed in the Outout window of the IDE. (Figure-1.16 below)
Human Sang Shin walks…
Human Sang Shin walks…
Monkey MonkeyWrench also walks…
human1.getName() = Sang Shin
livingthing1.getName() = Sang Shin
Do human1 and livingthing1 point to the same object instance? true

Figure-1.16: Result

7. For your own exercise, please do the following:

  • Define another abstract method in the LivingThing.java as following
    • public abstract void dance(String dancingStyle);
  • Implement a concrete method in the Human.java and Monkey.java
  • Modify Main.java to invoke dance(String dancingStyle) method through obect instances of human1 and livingthing1.
    • Example dancing styles could be Tango, ChaChaCha, or whatever

Solution: The solution to this exercise 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>/javainterface/samples/MyAbstractClassProject.  You can just open it and run it.

(1.2) Build MyOnlineShopUsingAbstractClass program

In this step, you are going to rewrite MyOnlineShop program you built and run in the Java Inheritance hands-on lab to use an abstract method of an abstract class (instead of overriding method of a concrete class).   The differences are highlighted in bold font.

The MyOnlineShop project is provided as part of this hands-on lab zip file for your convenience.  You can open it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyOnlineShop.  The instruction below is written with an assumption that you are stating from scratch.

1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select Java under Categories section and Java Application under Projects section.
  • Click Next.
  • Observe that the Name and Location pane appears.
  • For the Project Name field, enter MyOnlineShopUsingAbstractClass.
  • Click Finish.
  • Observe that the MyOnlineShopUsingAbstractClass project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.

2. Write Product.java.  The Product class is an abstract class that has an abstract method called computeSalePrice().

  • Right click MyOnlineShopUsingAbstractClass 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 Product.
  • For the Package field, either enter myonlineshop or choose myonlineshopfrom the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Product.java gets displayed in the editor window.
  • Modify the IDE generated Product.java as shown in Code-1.20 below.
package myonlineshop;// Product class is now an abstract class
public abstract class Product {

private double regularPrice;

/** Creates a new instance of Product */
public Product(double regularPrice) {
this.regularPrice = regularPrice;
}

// computeSalePrice() is now an abstract method
public abstract double computeSalePrice();

public double getRegularPrice() {
return regularPrice;
}

public void setRegularPrice(double regularPrice) {
this.regularPrice = regularPrice;
}

}

Code-1.20: Product.java

3. Write Electronics.java.  The Electronics class itself  is an abstract class because it does not provide implementation of the computeSalePrice() abstract method.

  • Right click MyFinalClassExample 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 Electronics.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Electronics.java gets displayed in the editor window.
  • Modify the IDE generated Electronics.java as shown in Code-1.21 below.  Note that Electronics class extends Product class.
package myonlineshop;// Electronics class is now an abstract class because
// it does not provide implementation of the
// computeSalePrice() abstract method.
public abstract class Electronics extends Product{

private String manufacturer;

/** Creates a new instance of Electronics */
public Electronics(double regularPrice,
String manufacturer) {
super(regularPrice);
this.manufacturer = manufacturer;
}

public String getManufacturer() {
return manufacturer;
}

public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}

}

Code-1.21: Electronics.java

4. Write MP3Player.java.  The MP3Player class extends Electronics class.  Note also that the MP3Player class has implementation of the computeSalePrice() method.

  • Right click MyFinalClassExample 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 MP3Player.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated MP3Player.java gets displayed in the editor window.
  • Modify the IDE generated MP3Player.java as shown in Code-1.23 below.
package myonlineshop;public class MP3Player extends Electronics{

private String color;

public MP3Player(double regularPrice,
String manufacturer,
String color) {
super(regularPrice, manufacturer);
this.color = color;
}

// Implement the abstract method
public double computeSalePrice(){
return super.getRegularPrice() * 0.9;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}

Code-1.23: MP3Player.java

5. Write TV.java.  The TV class extends Electronics abstract class.  Note also that the TV class has the implementation of the computeSalePrice() method.

  • Right click MyFinalClassExample 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 TV.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated TV.java gets displayed in the editor window.
  • Modify the IDE generated TV.java as shown in Code-1.24 below.
package myonlineshop;public class TV extends Electronics {

int size;

/** Creates a new instance of TV */
public TV(double regularPrice,
String manufacturer,
int size) {
super(regularPrice, manufacturer);
this.size = size;
}

// Implement the abstract method
public double computeSalePrice(){
return super.getRegularPrice() * 0.8;
}
}

Code-1.24: TV.java

6. Write Book.java.  The Book class extends Product class.  Note also that the Book class has the implementation of the computeSalePrice() method.

  • Right click MyFinalClassExample 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 Book.
  • For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Book.java gets displayed in the editor window.
  • Modify the IDE generated Book.java as shown in Code-1.25 below.
package myonlineshop;public class Book extends Product{

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;
}

// Implement the abstract 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-1.25: Book.java

7. Modify Main.java as shown in Code-1.26 below.  Study the code by special attention to the bold fonted comments,

package myonlineshop;public class Main {

public static void main(String[] args) {

// Declare and create Product array of size 5
Product[] pa = new Product[5];

// 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);

// 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-1.26: Main.java

8. Build and run the program.

  • Right click MyOnlineShopUsingAbstractClass and select Run.
  • Observe the result in the Output window of the IDE.  (Figure-1.27 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.27: Result

Solution: The solution to this step 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>/javainterface/samples/MyOnlineShopUsingAbstractClass.  You can just open it and run it.

Summary

In this exercise, you will build a simple program using an abstract class.  You also learned how to add polymorphic behavior to the program using abstract methods.

Exercise 2: Java Interface as a Type

In this exercise, you will build a simple Java application that uses Interface as a type.

(2.1) Build a Java program that uses Interface as a type

1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select Java under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyPersonInterface.  (Figure-2.10 below)
  • Click Finish.


Figure-2.10: Create MyPersonInterfaceProject

  • Observe that the MyPersonInterfaceProject project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.
2. Write PersonInterface.java.  The PersonInterface is Java interface.

  • Right click MyPersonInterfaceProject project node and select New->Java Class.  (You can choose New->Java Interface as well.)
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter PersonInterface.
  • For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.  (Figure-2.11 below)
  • Click Finish.


Figure-2.11: PersonInterface interface

  • Observe that IDE generated PersonInterface.java gets displayed in the editor window.
  • Modify the IDE generated PersonInterface.java as shown in Code-2.12 below.
package mypersoninterfaceproject;public interface PersonInterface {

// Compute person’s total wealth
int computeTotalWealth();

// Get person’s name
String getName();

}

Code-2.12: PersonInterface.java

3. Write Person.java.  The Person class implements PersonInterface interface.

  • Right click MyPersonInterfaceProjectproject 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 Person.
  • For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Person.java gets displayed in the editor window.
  • Modify the IDE generated Person.java as shown in Code-2.13 below.
  • Study the code by paying special attention to bold-fonted part.
package mypersoninterfaceproject;public class Person implements PersonInterface {

int cashSaving;
int retirementFund;
String firstName;
String lastName;

// Constructor with arguments
Person(int cashSaving,
int retirementFund,
String firstName,
String lastName){
this.cashSaving = cashSaving;
this.retirementFund = retirementFund;
this.firstName = firstName;
this.lastName = lastName;
}

// Compute person’s total wealth
public int computeTotalWealth(){
System.out.println((cashSaving + retirementFund));;
return (cashSaving + retirementFund);
}

// Get person’s name
public String getName(){
return firstName + ” ” + lastName;
}

}

Code-2.13: Person.java

4. Modify Main.java as shown in Code-2.14 below.  Study the code paying special attention to the bold-fonted part.

package mypersoninterfaceproject;public class Main {

public static void main(String[] args) {

// Create an object instance of Person class.
Person person1 = new Person(10000, 20000, “Sang”, “Shin”);

// You can assign the object instance to
// PersonInterface type.
PersonInterface personinterface1 = person1;

// Display data from person1 and personinterface1.
// Observe that they refer to the same object instance.
System.out.println(“person1.getName() = ” + person1.getName() + “,” +
” person1.computeTotalWealth() = ” + person1.computeTotalWealth());

System.out.println(“personinterface1.getName() = ” + personinterface1.getName() + “,” +
” personinterface1.computeTotalWealth() = ” + personinterface1.computeTotalWealth());

// Check of object instance that is referred by person1 and
// personinterface1 is the same object instance.
boolean b1 = (person1 == personinterface1);
System.out.println(“Do person1 and personinterface1 point to the same object instance? ” + b1);

// Create an object instance of Person class
// and assign it to the interface type directly.
PersonInterface personinterface2 = new Person(3000, 4000, “Dadu”, “Daniel”);

System.out.println(“personinterface2.getName() = ” + personinterface2.getName() + “,” +
” personinterface2.computeTotalWealth() = ” + personinterface2.computeTotalWealth());

}

}

Code-2.14: Main.java

5. Build and run the program.

  • Right click MyPersonInterfaceProject and select Run.
  • Observe the result in the Output window of the IDE.  (Figure-2.15 below)
30000
person1.getName() = Sang Shin, person1.computeTotalWealth() = 30000
30000
personinterface1.getName() = Sang Shin, personinterface1.computeTotalWealth() = 30000
Do person1 and personinterface1 point to the same object instance? true
7000
personinterface2.getName() = Dadu Daniel, personinterface2.computeTotalWealth() = 7000

Figure-2.15: Result

Solution: The solution to this step 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>/javainterface/samples/MyPersonInterfaceProject.  You can just open it and run it.

(2.2) Build a Java program that uses RelationInterface Interface

In this step, you are going to build another Java program that uses a Java interface called RelationInterface.

1. Create a NetBeans project

  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select Java under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyRelationInterfaceProject.
  • Click Finish.
  • Observe that the MyRelationInterfaceProject project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.

2. Write RelationInterface Java interface.

  • Right click MyPersonInterfaceProject project node and select New->Java Class.  (You can choose New->Java Interface as well.)
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter RelationInterface.
  • For the Package field, either enter myrelationinterfaceproject or choose myrelationinterfaceproject from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated RelationInterface.java gets displayed in the editor window.
  • Modify the IDE generated RelationInterface.java as shown in Code-2.21 below.
package myrelationinterfaceproject;// Define an interface with three abstract methods.
// Any class that implements this interface has to
// implement all three methods.
public interface RelationInterface {
public boolean isGreater( Object a, Object b);
public boolean isLess( Object a, Object b);
public boolean isEqual( Object a, Object b);
}

Code-2.21: RelationInterface.java

3. Write Line.java.  Line class implements RelationInterface interface.

  • Right click MyPersonInterfaceProjectproject 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 Line.
  • For the Package field, either enter myrelationinterfaceproject or choose myrelationinterfaceproject from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Line.java gets displayed in the editor window.
  • Modify the IDE generated Line.java as shown in Code-2.23 below.
package myrelationinterfaceproject;public class Line implements RelationInterface{

private double x1;
private double x2;
private double y1;
private double y2;

// Constructor methoe of the Line class.
public Line(double x1,double x2,double y1,double y2){
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}

// A new method definition of the Line class
public double getLength(){
double length = Math.sqrt(    (x2-x1)*(x2-x1) +
(y2-y1)*(y2-y1));
return length;
}

// Implement isGreater(..) method defined in the Relation interface
public boolean isGreater( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen > bLen);
}

// Implement isLess(..) method defined in the Relation interface
public boolean isLess( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen < bLen);
}

// Implement isEqual(..) method defined in the Relation interface
public boolean isEqual( Object a, Object b){
double aLen = ((Line)a).getLength();
double bLen = ((Line)b).getLength();
return (aLen == bLen);
}

}

Code-2.23: Line.java

4. Modify Main.java as shown in Code-2.24 below.  Study the code paying special attention to the bold-fonted part.

package myrelationinterfaceproject;public class Main {

public static void main(String[] args) {

// Create two Line object instances.
Line line1  = new Line(1.0, 2.0, 1.0, 2.0);
Line line2  = new Line(2.0, 3.0, 2.0, 3.0);

boolean b1 = line1.isGreater(line1, line2);
System.out.println(“line1 is greater than line2: ” + b1);
boolean b2 = line1.isEqual(line1, line2);
System.out.println(“line1 is equal with line2: ” + b2);

// Note that the line3 is object instance of Line type.
// Because the Line type is also a type of RelationInterface,
// the line3 variable can be declared as RelationInterface type.
// This is a very very important concept you need to understand.
RelationInterface line3  = new Line(1.0, 5.0, 1.0, 5.0);
boolean b3 = line3.isEqual(line1, line3);
System.out.println(“line1 is equal with line3: ” + b3);

System.out.println(“Length of line1 is ” + line1.getLength());
System.out.println(“Length of line2 is ” + line2.getLength());

// The following line of code will generate a compile error since line3
// is declared as RelationInterface interface type not Line type
// and the getLength() method is not one of the methods defined
// in the RelationInterface interface.  It is commented out for now.
// System.out.println(“Length of line3 is ” + line3.getLength());
}

}

Code-2.24: Main.java

5. Build and run the program

  • Right click MyRelationInterfaceProject and select Run.
  • Observe the result in the Output window of the IDE.  (Figure-2.25 below)
line1 is greater than line2: false
line1 is equal with line2: true
line1 is equal with line3: false
Length of line1 is 1.4142135623730951
Length of line2 is 1.4142135623730951

Figure-2.25: Result

6.  For your own exercise, do the following.

  • Uncomment the last commented line of the Main.java that contains line3.getLength() and observe the compile error.
  • Understand why the compiler error occurs.

Solution: The solution to this step 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>/javainterface/samples/MyRelationInterfaceProject.  You can just open it and run it.

Summary

In this exercise, you built two Java programs which use Java interface.  You learned how a Java interface is used as a type.  You learned how a concrete class implements a Java interface.

 

Exercise 3: Implementing multiple Interfaces

In this exercise, you are going to learn a how a concrete class can implement multiple Java interfaces.

  1. Build and run a Java program that uses multiple Java interfaces

(3.1) Build and run a Java program that uses multiple Java interfaces

You can use the MyPersonInterfaceProject project you built above for the change you are going to make in this exercise or you might want to create a new project, for example, MyPersonMultipleInterfaces, by “copying” MyPersonInterfaceProject project – Right click MyPersonInterfaceProject project and select Copy Project.  This document assumed you have created MyPersonMultipleInterfaces project.1. Write AnotherInterfaceExample.java.  AnotherInterfaceExample interface is the 2nd Java interface that we want to add to the program.

  • Right click MyPersonInterfaceProject 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 AnotherInterfaceExample
  • For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated AnotherInterfceExample.java gets displayed in the editor window.
  • Modify the IDE generated AnotherInterfceExample.java as shown in Code-3.10 below.
package mypersoninterfaceproject;public interface AnotherInterfaceExample {

// Measure person’s intelligence
int measureIntelligence(String name);

}

Code-3.10: AnotherInterfaceExample.java

2. Modify Person.java as shown in Code-3.11 below.  The change is to have the Person class to implement the AnotherInterfaceExample interface in addition to PersonInterface interface.  The code fragments that need to be added are highlighted in bold and blue-colored font.

package mypersoninterfaceproject;public class Person implements PersonInterface,
AnotherInterfaceExample{

int cashSaving;
int retirementFund;
String firstName;
String lastName;

// Constructor with arguments
Person(int cashSaving,
int retirementFund,
String firstName,
String lastName){
this.cashSaving = cashSaving;
this.retirementFund = retirementFund;
this.firstName = firstName;
this.lastName = lastName;
}

// Compute person’s total wealth
public int computeTotalWealth(){
System.out.println((cashSaving + retirementFund));;
return (cashSaving + retirementFund);
}

// Get person’s name
public String getName(){
return firstName + ” ” + lastName;
}

// Implement method of AnotherInterfaceExample
public int measureIntelligence(String name){
if (name.startsWith(“smart”)){
return 100;
}
else{
return 50;
}
}

}

Code-3.11: Modified Person.java

3. Modify Main.java as shown in Code-3.12 below. The change is to show that now the object instance of the Person class now can invoke the method defined in the new interface.   The code fragments that need to be changed are highlighted in bold and blue-colored font.

package mypersoninterfaceproject;
public class Main {public static void main(String[] args) {

// Create an object instance of Person class.
Person person1 = new Person(10000, 20000, “Sang”, “Shin”);

// You can assign the object instance to
// PersonInterface type.
PersonInterface personinterface1 = person1;

// Display data from person1 and personinterface1.
// Observe that they refer to the same object instance.
System.out.println(“person1.getName() = ” + person1.getName() + “,” +
” person1.computeTotalWealth() = ” + person1.computeTotalWealth() + “,” +
” person1.measureIntelligence() = ” + person1.measureIntelligence(person1.getName()));

System.out.println(“personinterface1.getName() = ” + personinterface1.getName() + “,” +
” personinterface1.computeTotalWealth() = ” + personinterface1.computeTotalWealth());

// Compile error is expected on the following line of code.
// personinterface1.measureIntelligence(personinterface1.getName());

// You can assign the object instance to
// AnotherInterfaceExample type.
AnotherInterfaceExample anotherinterfaceexample1 = person1;

// Check of object instance that is referred by personinterface1 and
// anotherinterfaceexample1 is the same object instance.
boolean b1 = (personinterface1 == anotherinterfaceexample1);
System.out.println(“Do personinterface1 and anotherinterfaceexample1 point to the same object instance? ” + b1);

}

}

Code-3.12: Modified Main.java

 

4. Build and run the program.

  • Right click MyPersonMultipleInterfaces and select Run.
  • Observe the result in the Output window of the IDE.
30000
person1.getName() = Sang Shin, person1.computeTotalWealth() = 30000, person1.measureIntelligence() = 50
30000
personinterface1.getName() = Sang Shin, personinterface1.computeTotalWealth() = 30000
Do personinterface1 and anotherinterfaceexample1 point to the same object instance? true

Code-3.13: Result

Solution: The solution to this step 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>/javainterface/samples/MyPersonMultipleInterfaces.  You can just open it and run it.

5. For your own exercise, please do the following:

  • Add the 3rd interface with the following mtehod
    • int computeFirstNameLength(String name);
  • Make the Person class to implement the 3rd interface
    • The implementation of the computeFirstNameLength(String name) returns the length of the first name
  • Modify Main.java to display information accordingly

Summary

In this exercise, you have reimplemented MyPersonInterfaceProject to have the Person class to implement multiple Java interfaces.

 

 

Exercise 4: Inheritance and polymorphism

In this exercise, you are going to rewrite MyOnlineShopUsingAbstractClass program you built above to use Java interface (instead of Abstract class).

  1. Build MyOnlineShopUsingInterface project

(4.1) Build MyOnlineShopUsingInterface project

1. Create a NetBeans project
  • Select File from top-level menu and select New Project.
  • Observe that the New Project dialog box appears.
  • Select Java under Categories section and Java Application under Projects section.
  • Click Next.
  • Under Name and Location pane, for the Project Name field, enter MyOnlineShopUsingInterface. (Figure-1.10 below)
  • Click Finish.
  • Observe that the MyOnlineShopUsingInterface project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.
2. Write ProductInterface.java.

  • Right click MyOnlineShopUsingInterface project node and select New->Java Class. (You can choose New->Java Interface)
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter ProductInterface.
  • For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated ProductInterface.java gets displayed in the editor window.
  • Modify the IDE generated ProductInterface.java as shown in Code-4.11 below.
package myonlineshopusinginterface;public interface ProductInterface {
public double computeSalePrice();
public double getRegularPrice();
public void setRegularPrice(double regularPrice);
}

Code-4.11: ProductInterface.java

3. Write Product.java.

  • Right click MyOnlineShopUsingInterface 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 Product.
  • For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Product.java gets displayed in the editor window.
  • Modify the IDE generated Product.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class Product implements ProductInterface{

private double regularPrice;

/** Creates a new instance of Product */
public Product(double regularPrice) {
this.regularPrice = regularPrice;
}

// Implement the methods of the ProductInterface
public double computeSalePrice(){
return 0;
}

public double getRegularPrice() {
return regularPrice;
}

public void setRegularPrice(double regularPrice) {
this.regularPrice = regularPrice;
}

}

Code-4.12: Product.java

4. Write ElectronicsInterface.java.  The ElectronicsInterface is a Java interface which extends ProductInterface interface.

  • Right click MyOnlineShopUsingInterface project node and select New->Java Class. (You can choose New->Java Interface)
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter ElectronicsInterface.
  • For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
  • Click Finish.
  • Observe that IDE generate ElectronicsInterface.java gets displayed in the editor window.
  • Modify the IDE generated ElectronicsInteface.java as shown in Code-4.13 below.
package myonlineshopusinginterface;public interface ElectronicsInterface extends ProductInterface {

public String getManufacturer();

}

Code-4.12: ElectronicsInterface.java

5. Write Electronics.java.

  • Right click MyOnlineShopUsingInterface 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 Electronics.
  • For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Electronics.java gets displayed in the editor window.
  • Modify the IDE generated Electronics.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class Electronics extends Product implements ElectronicsInterface {

private String manufacturer;

/** Creates a new instance of Electronics */
public Electronics(double regularPrice,
String manufacturer) {
super(regularPrice);
this.manufacturer = manufacturer;
}

public String getManufacturer() {
return manufacturer;
}

public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
}

Code-4.12: Electronics.java

6. Write MP3Player.java.

  • Right click MyOnlineShopUsingInterface 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 MP3Player.
  • For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated MP3Player.java gets displayed in the editor window.
  • Modify the IDE generated MP3Player.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class MP3Player extends Electronics{

private String color;

public MP3Player(double regularPrice,
String manufacturer,
String color) {
super(regularPrice, manufacturer);
this.color = color;
}

// Override the method
public double computeSalePrice(){
return super.getRegularPrice() * 0.9;
}

public String getColor() {
return color;
}

public void setColor(String color) {
this.color = color;
}
}

Code-4.12: MP3Player.java

7. Write TV.java.

  • Right click MyOnlineShopUsingInterface 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 TV.
  • For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated TV.java gets displayed in the editor window.
  • Modify the IDE generated TV.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class TV extends Electronics {

int size;

/** Creates a new instance of TV */
public TV(double regularPrice,
String manufacturer,
int size) {
super(regularPrice, manufacturer);
this.size = size;
}

// Override the method
public double computeSalePrice(){
return super.getRegularPrice() * 0.8;
}
}

Code-4.12: TV.java

8. Write Book.java.

  • Right click MyOnlineShopUsingInterface 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 Book.
  • For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Book.java gets displayed in the editor window.
  • Modify the IDE generated Book.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class Book extends Product {

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-4.12: Book.java

9. Modify Main.java as shown in Code-3.12 below.

package myonlineshopusinginterface;public class Main {

/** Creates a new instance of Main */
public Main() {
}

public static void main(String[] args) {

// Declare and create Product array of size 5
ProductInterface[] pa = new Product[5];

// 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);

// 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.12: Modified Main.java

4. Build and run the program

  • Right click MyOnlineShopUsingInterface and select Run.
  • Observe the result in the Output window of the IDE.
Item number 0: Type = myonlineshopusinginterface.TV, Regular price = 1000.0, Sale price = 800.0
Item number 1: Type = myonlineshopusinginterface.TV, Regular price = 2000.0, Sale price = 1600.0
Item number 2: Type = myonlineshopusinginterface.MP3Player, Regular price = 250.0, Sale price = 225.0
Item number 3: Type = myonlineshopusinginterface.Book, Regular price = 34.0, Sale price = 17.0
Item number 4: Type = myonlineshopusinginterface.Book, Regular price = 15.0, Sale price = 7.5
totalRegularPrice = 3299.0
totalSalePrice = 2649.5

Code-3.13: Result

Solution: The solution to this step 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>/javainterface/samples/MyOnlineShopUsingInterface.  You can just open it and run it.

Summary

In this exercise, you have rewritten MyOnlineShop application using Java interfaces.

Exercise 5: Inheritance among Interfaces

Interfaces can have inheritance relationship among themselves.

  1. Build and run a Java program that uses Java interfaces that are related through inheritance

(5.1) Build and run a Java program that uses Java interfaces that are related through inheritance

You can use the MyPersonInterfaceProject project for the change you are going to make in this exercise or you might want to create a new project, for example, MyPersonInheritanceInterfaces, by “copying” MyPersonInterfaceProject project – Right click MyPersonInterfaceProject project and select Copy Project.  This document assumed you have created MyPersonInheritanceInterfaces project.1. Write StudentInterface.java. The StudentInterface interface extends PersonInterface.  In other words, StudentInterface interface is a child interface of the PersonInterface.

  • Right click MyPersonInheritanceInterfacesproject node and select New->Java Class. (You can choose New->Java Interface as well.)
  • Observe Name and Location pane of the New Java Class dialog box appears.
  • For the Class Name field, enter StudentInterface
  • For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated StudentInterface.java gets displayed in the editor window.
  • Modify the IDE generated StudentInterface.java as shown in Code-5.10 below.
  • Study the code by paying attention to the bold-fonted part.
package mypersoninterfaceproject;// StudentInterface interface extends PersonInteface interface
public interface StudentInterface extends PersonInterface{

// Find the school the student attends
String findSchool();

}

Code-5.10: StudentInterface.java

2. Write Student.java.  The Student class implements StudentInterface interface.   The Student class implements all the methods defined in the StudentInterface interface and its parent interfaces.

  • Right click MyOnlineShopUsingAbstractClass 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 Student.
  • For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Student.java gets displayed in the editor window.
  • Modify the IDE generated Student.java as shown in Code-5.11 below.
package mypersoninterfaceproject;public class Student implements StudentInterface {

int cashSaving;
int retirementFund;
String firstName;
String lastName;
String school;

// Constructor with arguments
Student(int cashSaving,
int retirementFund,
String firstName,
String lastName,
String school){
this.cashSaving = cashSaving;
this.retirementFund = retirementFund;
this.firstName = firstName;
this.lastName = lastName;
this.school = school;
}

// Compute person’s total wealth
public int computeTotalWealth(){
System.out.println((cashSaving + retirementFund));
return (cashSaving + retirementFund);
}

// Get person’s name
public String getName(){
return firstName + ” ” + lastName;
}

// Find out the school the student attends
public String findSchool(){
return school;
}
}

Code-5.11: Modified Student.java

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

package mypersoninterfaceproject;public class Main {

public static void main(String[] args) {

// Create an object instance of Student class.
Student student1 = new Student(10000, 20000, “Sang”, “Shin”, “Good School”);

// You can assign the object instance to
// StudentInterface type.
StudentInterface studentinterface1 = student1;

// Display data from student1 and studentinterface1.
// Observe that they refer to the same object instance.
System.out.println(“student1.getName() = ” + student1.getName() + “,” +
” student1.computeTotalWealth() = ” + student1.computeTotalWealth()+ “,” +
” student1.findSchool() = ” + student1.findSchool());

System.out.println(“studentinterface1.getName() = ” + studentinterface1.getName() + “,” +
” studentinterface1.computeTotalWealth() = ” + studentinterface1.computeTotalWealth()+ “,” +
” studentinterface1.findSchool() = ” + studentinterface1.findSchool());

// Check of object instance that is referred by student1 and
// studentinterface1 is the same object instance.
boolean b1 = (student1 == studentinterface1);
System.out.println(“Do student1 and studentinterface1 point to the same object instance? ” + b1);

}

}

Code-5.12: Modified Main.java

4. Build and run the program

  • Right click MyPersonInheritanceInterfaces and select Run.
  • Observe the result in the Output window of the IDE. (Figure-5.13 below)
30000
student1.getName() = Sang Shin, student1.computeTotalWealth() = 30000, student1.findSchool() = Good School
30000
studentinterface1.getName() = Sang Shin, studentinterface1.computeTotalWealth() = 30000, studentinterface1.findSchool() = Good School
Do student1 and studentinterface1 point to the same object instance? true

Figure-5.13: Result

Solution: The solution to this step 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>/javainterface/samples/MyPersonInheritanceInterfaces.  You can just open it and run it.

Summary

In this exercise, you built a Java program which uses a Java interface which is a child interface of another interface.

Exercise 6: Rewriting an Interface

In this exercise, you are going to learn how to handle adding new methods to a existing Java interface without breaking existing applications that use the interface.
  1. Try to add another method to the PersonInterface interface

(6.1) Try to add another method the PersonInterface interface

You can use the MyPersonInterfaceProject project for the change you are going to make in this exercise or you might want to create a new project, for example, MyRewritingInterface, by “copying” MyPersonInterfaceProject project – Right click MyPersonInterfaceProject project and select Copy Project.  This document assumed you have created MyRewritingInterface project.1. Modify PersonInterface.java as shown in Code-6.11 below.  The change is to another method to the PersonInterface.java.  The code fragments that need to be added are highlighted in bold and blue-colored font.

package mypersoninterfaceproject;public interface PersonInterface {

// Compute person’s total wealth
int computeTotalWealth();

// Get person’s name
String getName();

// Add another method to the interface
void newMethod();

}

Code-6.11: Modified PersonInterface.java

2. Observe the compile error in the Person.java.  (Figure-6.12 below)

<Learning point> It is not unusual to have one developer (or one Java API specification group) defines a set of Java interfaces and other developers (or groups) implement them.  Now if the interface is changed (adding another method to it), the existing implementation classes will be broken.  That is what you observed in this step.  The solution to this problem is to define another Java interface that contains only the newly added method.


Figure-6.12: The Person class is now broken

3. Remove the change you made in PersonInterface.java in the previous step as shown in Code-6.13 below.  This is the original code before thd change.

package mypersoninterfaceproject;public interface PersonInterface {

// Compute person’s total wealth
int computeTotalWealth();

// Get person’s name
String getName();

}

Code-6.13: PersonInterface.java

4. Write PersonInterfaceAnother.java.  The PersonInterfaceAnother interface is a newly created interface that contains newly added method.

package mypersoninterfaceproject;public interface PersonInterfaceAnother {

// Add another method to the interface
void newMethod();

}

Code-6.14: PersonInterfaceAnother.java

5. Write PersonAnother.java.  The PersonAnother class implements both Person and PersonInterfaceAnother interfaces.

package mypersoninterfaceproject;public class PersonAnother implements PersonInterface,
PersonInterfaceAnother{

int cashSaving;
int retirementFund;
String firstName;
String lastName;

// Constructor with arguments
PersonAnother(int cashSaving,
int retirementFund,
String firstName,
String lastName){
this.cashSaving = cashSaving;
this.retirementFund = retirementFund;
this.firstName = firstName;
this.lastName = lastName;
}

// Compute person’s total wealth
public int computeTotalWealth(){
System.out.println((cashSaving + retirementFund));
return (cashSaving + retirementFund);
}

// Get person’s name
public String getName(){
return firstName + ” ” + lastName;
}

// Implement a new method
public void newMethod(){
// Some code
}

}

Code-6.15: PersonAnother.java

6. Write PersonAnother2.java.  The PersonAnother2 class extends Person class and implements PersonInterfaceAnother interface.

package mypersoninterfaceproject;public class PersonAnother2 extends Person implements PersonInterfaceAnother{

PersonAnother2(){

}

// Implement a new method
public void newMethod(){
// Some code
}
}

Code-6.16: PersonAnother2.java

Solution: The solution to this step 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>/javainterface/samples/MyRewritingInterface.  You can just open it and run it.

7. For your exercise, please do the following tasks:

  • Create another interface called PersonInterface3 with the following method
    • String toChangeNameToUpperCase() // Change name to upper case
  • Create another implementation class called PersonAnother3 that implements PersonInterface, PersonInterface2, PersonInterface interfaces
  • Modify Main.java to create a object  instance of PersonAnother3 and display the name in upper case.

Summary

In this exercise, you have learned how to add new methods to the Java interface without breaking existing code that depends on the existing Java interface.

 

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

 

1. The homework is to modify the MyPersonMultipleInterfaces project above.   (You might want to create a new project by copying the MyGetPersonMultipleInterfaces project.)  You can name the new project in any way you want but here I am going to call to call it as MyGetPersonMultipleInterfaces2.
  • Write an interface called MyOwnInterface, which has the following method
    • AddressInterface getAddress();
  • The AddressInterface is a Java interface that has the following methods.
    • int getStreetNumber();
    • void setStreetNumber(int streetNumber);
    • String getStreetName();
    • void setStreetName(String streetName);
    • String getCountry();
    • void setCountry(String country);
  • Write AddressImpl class that implements AddressInterface
  • Make the Person class to implement MyOwnInterface.
  • Initialize a Person object with proper data and display it.
2. Send the following files to javaprogramminghomework@sun.com with Subject as JavaIntro-javainterface.
  • Zip file of the the MyGetPersonMultipleInterfaces2 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 MyGetPersonMultipleInterfaces2 directory> (assuming you named your project as MyGetPersonMultipleInterfaces2)
    • jar cvf MyGetPersonMultipleInterfaces2.zip MyGetPersonMultipleInterfaces2 (MyGetPersonMultipleInterfaces2 should contain nbproject directory)
  • Captured output screen  – name it as JavaIntro-javainterface.gif orJavaIntro-javainterface.jpg (or JavaIntro-javainterface.<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.

 

답글 남기기

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

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