목요일, 4월 18
Shadow

#012 Java Inheritance

 

Lab Exercises

 

Exercise 1: Build and run a Java program which uses classes that are related through Inheritance

In this exercise, you are going to write a program in which multiple classes, which are related with inheritance, are created and used.  First, you will create Person class.  Then you will create sub-classes of the Person class, Student class and Teacher class.  You will also create sub-class of the Student class, which is called InternationalStudent class.

(1.1) Build and run a Java program that uses classes that are related

0. Start the 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.

  • Observe that the Name and Location pane appears.
  • For the Project Name field, enter MyPeopleExample. (Figure-1.10 below)
  • Click Finish.


Figure-1.10: Create a new project

  • Observe that the MyPeopleExample 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 Person.java.

  • Right click MyPeopleExample 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 Person.
  • For the Package field, either enter mypeopleexample or choose mypeopleexample from the drop-down menu. (Figure-1.11 below)
  • Click Finish.


Figure-1.11: Create a Person.java

  • Observe that IDE generated Person.java gets displayed in the editor window.
  • Modify the IDE generated Person.java as shown in Code-1.12 below.  Note that the Person class has two fields, name and address, and getter and setter methods of them.
package mypeopleexample;public class Person {

private String name;
private String address;

public String getName() {
return name;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

Code-1.12: Person.java

3. Write Student.java. Note that the Student class is a sub-class of the Person class.

  • Right click MyPeopleExample 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 mypeopleexample or choose mypeopleexample from the drop-down menu. (Figure-1.11 below)
  • Click Finish.

  • Observe that IDE generated Student.java gets displayed in the editor window.
  • Modify the IDE generated Student.java as shown in Code-1.13 below.  Note that the Student class has two fields, school and grade, and getter and setter methods of them.
package mypeopleexample;public class Student extends Person {

private String school;
private double grade;

public String getSchool() {
return school;
}

public void setSchool(String school) {
this.school = school;
}

public double getGrade() {
return grade;
}

public void setGrade(double grade) {
this.grade = grade;
}
}

Code-1.13: Student.java

4. Write InternationalStudent.java. Note that  InternationalStudent class is a sub-class of Student class.

  • Right click MyPeopleExample 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 InternationalStudent.
  • For the Package field, either enter mypeopleexample or choose mypeopleexample from the drop-down menu.
  • Click Finish.

  • Observe that IDE generated InternationalStudent.java gets displayed in the editor window.
  • Modify the IDE generated InternationalStudent.java as shown in Code-1.14 below.  Note that the InternationalStudent class has one field, country, and getter and setter methods.
package mypeopleexample;public class InternationalStudent extends Student {

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

private String country;

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

}

Code-1.14: InternationalStudent.java

5. Write Teacher.java.  Note that Teacher class is a sub-class of Person class.

  • Right click MyPeopleExample 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 Teacher.
  • For the Package field, either enter mypeopleexample or choose mypeopleexample from the drop-down menu.
  • Click Finish.

  • Observe that IDE generated Teacher.java gets displayed in the editor window.
  • Modify the IDE generated Teacher.java as shown in Code-1.16 below. Note that the Teacher class has one field, subject, and getter and setter methods of it.
package mypeopleexample;public class Teacher extends Person {

private String subject;

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}
}

Code-1.16: Teacher.java

6. Modify Main.java.

  • Modify the Main.java as shown in Code-1.17 below. The change is to create object instances of the Person, Student, InternationalStudent, and Teacher classes.
package mypeopleexample;public class Main {

public static void main(String[] args) {

// Create object instances and invoke methods.
// Note that you can use methods defined in a parent
// class for object instances of the child class.

Person person1 = new Person();
person1.setName(“Tom Jones”);

Student student1 = new Student();
student1.setName(“CCR”);
student1.setSchool(“Lexington High”);

InternationalStudent internationalStudent1 =
new InternationalStudent();
internationalStudent1.setName(“Bill Clinton”);
internationalStudent1.setSchool(“Lexington High”);
internationalStudent1.setCountry(“Korea”);

Teacher teacher1 = new Teacher();
teacher1.setName(“Beatles”);
teacher1.setSubject(“History”);

// Display name of object instances using the getName() method
// defined in the Person class.
System.out.println(“Displaying names of all object instances…”);
System.out.println(”  person1.getName() = ” + person1.getName());
System.out.println(”  student1.getName() = ” + student1.getName());
System.out.println(”  internationalStudent1.getName() = ” +
internationalStudent1.getName());
System.out.println(”  teacher1.getName() = ” + teacher1.getName());

}
}

Code-1.17: Main.java

7. Build and run the program.

  • Right click MyPeopleExample and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-1.18 below)
Displaying names of all object instances…
person1.getName() = Tom Jones
student1.getName() = CCR
internationalStudent1.getName() = Bill Clinton
teacher1.getName() = Beatles

Figure-1.18: Result of running the application

(1.3) Display the class inheritance hierarchy through getSuperclass() method of the Class class

In this step, you are going to display the class hierarchy through a programming API – getSuperclass() method of a Class class – in your program.1. Modify Main.java as shown in Code-1.30 below.  The code fragment that need to be added are highlighted in bold and blue-colored font.

package mypeopleexample;public class Main {

public static void main(String[] args) {

// Create object instances and invoke methods.
// Note that you can use methods defined in a parent
// class for object instances of the child class.

Person person1 = new Person();
person1.setName(“Tom Jones”);

Student student1 = new Student();
student1.setName(“CCR”);
student1.setSchool(“Lexington High”);

InternationalStudent internationalStudent1 =
new InternationalStudent();
internationalStudent1.setName(“Bill Clinton”);
internationalStudent1.setSchool(“Lexington High”);
internationalStudent1.setCountry(“Korea”);

Teacher teacher1 = new Teacher();
teacher1.setName(“Beatles”);
teacher1.setSubject(“History”);

// Display name of object instances using the getName() method
// defined in the Person class.
System.out.println(“Displaying names of all object instances…”);
System.out.println(”  person1.getName() = ” + person1.getName());
System.out.println(”  student1.getName() = ” + student1.getName());
System.out.println(”  internationalStudent1.getName() = ” +
internationalStudent1.getName());
System.out.println(”  teacher1.getName() = ” + teacher1.getName());

// Display the class hierarchy of the InternationalStudent
// class through getSuperclass() method of Class class.
Class class1 = internationalStudent1.getClass();

System.out.println(“Displaying class hierarchy of InternationalStudent Class…”);
while (class1.getSuperclass() != null){
String child = class1.getName();
String parent = class1.getSuperclass().getName();
System.out.println(”  ” + child + ” class is a child class of ” + parent);
class1 = class1.getSuperclass();
}
}
}

Code-1.30: Modified Main.java

2. Build and run the program.

  • Right click MyPeopleExample and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-1.31 below)
Displaying names of all object instances…
person1.getName() = Tom Jones
student1.getName() = CCR
internationalStudent1.getName() = Bill Clinton
teacher1.getName() = Beatles
Displaying class hierarchy of InternationalStudent Class…
mypeopleexample.InternationalStudent class is a child class of mypeopleexample.Student
mypeopleexample.Student class is a child class of mypeopleexample.Person
mypeopleexample.Person class is a child class of java.lang.Object

Figure-1.31: Result of running the application

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>/javainheritance/samples/MyPeopleExample.  You can just open it and run it.

 

Summary

In this exercise, you have learned how to create object instances that are related through inheritance.

 

Exercise 2: Constructor calling chain

In this exercise, you are going to exercise the concept of constructor calling chain and how to use super() method and super reference.

 

(2.1) Constructor call chain

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyPeopleExampleConstructor, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumed you have created a new project.1. Modify Person.java as shown in Code-2.10 below.  The change is to add a display statement within the constructor.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Person {

public Person() {
System.out.println(“Person: constructor is called”);
}

private String name;
private String address;

public String getName() {
return name;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

Code-2.11: Person.java

2. Modify Student.java as shown in Code-2.11 below.  The change is to add a display statement within the constructor.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Student extends Person {

public Student() {
System.out.println(“Student: constructor is called”);
}

private String school;
private double grade;

public String getSchool() {
return school;
}

public void setSchool(String school) {
this.school = school;
}

public double getGrade() {
return grade;
}

public void setGrade(double grade) {
this.grade = grade;
}
}

Figure-2.12: Result of running the application

3. Modify InternationalStudent.java as shown in Code-2.12 below.  The change is to add a display statement within the constructor.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class InternationalStudent extends Student {

public InternationalStudent() {
System.out.println(“InternationalStudent: constructor is called”);
}

private String country;

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

}

Code-2.13: Code that generates compile error.

4. Modify Teacher.java as shown in Code-2.14 below.  The change is to add a display statement within the constructor.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Teacher extends Person {

public Teacher() {
System.out.println(“Teacher: constructor is called”);
}

private String subject;

public String getSubject() {
return subject;
}

public void setSubject(String subject) {
this.subject = subject;
}
}

Code-2.14: Code that generates compile error.

5. Modify Main.java as shown in Code-2.15 below.  The change is to add a display statement within the constructor.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Main {

public static void main(String[] args) {

// Create an object instance of
// InternationalStudent class.
System.out.println(“—- About to create an object instance of InternationalStudent class…”);
InternationalStudent internationalStudent1 =
new InternationalStudent();

// Create an object instance of
// Teacher class.
System.out.println(“—- About to create an object instance of Teacher class…”);
Teacher teacher1 = new Teacher();

}
}

Code-2.15: Modified Main.java

6. Build and run the program.

  • Right click MyPeopleExampleConstructor and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-2.16 below)
—- About to create an object instance of InternationalStudent class…
Person: constructor is called
Student: constructor is called
InternationalStudent: constructor is called
—- About to create an object instance of Teacher class…
Person: constructor is called
Teacher: constructor is called

Figure-2.16: 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>/javainheritance/samples/MyPeopleExampleConstructor.  You can just open it and run it.

(2.2) super() method

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyPeopleExampleConstructorSuper, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumed you have created a new project.1. Modify Person.java as shown in Code-2.10 below.  The change is to add another constructor that can be called from a sub class.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Person {

public Person() {
System.out.println(“Person: constructor is called”);
}

public Person(String name) {
this.name = name;
System.out.println(“Person: constructor 2 is called”);
}

private String name;
private String address;

public String getName() {
return name;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

Code-2.11: Person.java

2. Modify Student.java as shown in Code-2.11 below.  The change is to call the constructor method of the super class using super() method.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Student extends Person {

public Student() {
System.out.println(“Student: constructor is called”);
}

public Student(String name, String school, double grade) {
super(name);
this.school = school;
this.grade = grade;
System.out.println(“Student: constructor 2 is called”);
}

private String school;
private double grade;

public String getSchool() {
return school;
}

public void setSchool(String school) {
this.school = school;
}

public double getGrade() {
return grade;
}

public void setGrade(double grade) {
this.grade = grade;
}
}

Figure-2.12: Result of running the application

3. Modify InternationalStudent.java as shown in Code-2.12 below.  The change is to call the constructor method of the super class using super() method.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class InternationalStudent extends Student {

public InternationalStudent() {
System.out.println(“InternationalStudent: constructor is called”);
}

public InternationalStudent(String name, String school, double grade, String country) {
super(name, school, grade);
this.country = country;
System.out.println(“InternationalStudent: constructor 2 is called”);
}

private String country;

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

}

Code-2.13: Code that generates compile error.

4. Modify Main.java as shown in Code-2.12 below.  The change is to create an object instance of InternationalStudent class with initialization parameters.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Main {

public static void main(String[] args) {

// Create an object instance of
// InternationalStudent class.
System.out.println(“—- About to create an object instance of InternationalStudent class…”);
InternationalStudent internationalStudent1 =
new InternationalStudent(“Sang Shin”,   // Name
“1 Dreamland”, // Address
4.5,           // Grade
“Korea”);      // Country

System.out.println(“internationalStudent1.getName() = ” + internationalStudent1.getName());
System.out.println(“internationalStudent1.getAddress() = ” + internationalStudent1.getAddress());
System.out.println(“internationalStudent1.getGrade() = ” + internationalStudent1.getGrade());
System.out.println(“internationalStudent1.getCountry() = ” + internationalStudent1.getCountry());
}
}

Code-2.14: Code that generates compile error.

5. Build and run the program.

  • Right click MyPeopleExampleConstructorSuper and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-2.15 below)
—- About to create an object instance of InternationalStudent class…
Person: constructor 2 is called
Student: constructor 2 is called
InternationalStudent: constructor 2 is called
internationalStudent1.getName() = Sang Shin
internationalStudent1.getAddress() = null
internationalStudent1.getGrade() = 4.5
internationalStudent1.getCountry() = Korea

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>/javainheritance/samples/MyPeopleExampleConstructorSuper.  You can just open it and run it.

(2.3) super reference

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyPeopleExampleConstructorSuper2, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumes you have created a new project.1. Modify Person.java as shown in Code-2.10 below.  The change is to change the access modifiers of the fields to protected so that they can be accessed from sub classes.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Person {

public Person() {
System.out.println(“Person: constructor is called”);
}

public Person(String name) {
this.name = name;
System.out.println(“Person: constructor 2 is called”);
}

protected String name;
protected String address;

public String getName() {
return name;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

}

Code-2.11: Person.java

2. Modify Student.java as shown in Code-2.11 below.  The change is to change the access modifiers of the fields to protected so that they can be accessed from sub classes.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Student extends Person {

public Student() {
System.out.println(“Student: constructor is called”);
}

public Student(String name, String school, double grade) {
super(name);
this.school = school;
this.grade = grade;
System.out.println(“Student: constructor 2 is called”);
}

protected String school;
protected double grade;

public String getSchool() {
return school;
}

public void setSchool(String school) {
this.school = school;
}

public double getGrade() {
return grade;
}

public void setGrade(double grade) {
this.grade = grade;
}
}

Figure-2.12: Result of running the application

3. Modify InternationalStudent.java as shown in Code-2.12 below.   The change is to change the access modifiers of the fields to protected so that they can be accessed from the sub class.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class InternationalStudent extends Student {

public InternationalStudent() {
System.out.println(“InternationalStudent: constructor is called”);
}

public InternationalStudent(String name, String school, double grade, String country) {
super.name = name;
super.school = school;
super.grade = grade;
this.country = country;
System.out.println(“InternationalStudent: constructor 2 is called”);
}

private String country;

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

}

Code-2.13: Code that generates compile error.

4. Build and run the program.

  • Right click MyPeopleExampleConstructorSuper2 and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-2.15 below)
—- About to create an object instance of InternationalStudent class…
Person: contructor is called
Student: contructor is called
InternationalStudent: contructor 2 is called
internationalStudent1.getName() = Sang Shin
internationalStudent1.getAddress() = null
internationalStudent1.getGrade() = 4.5
internationalStudent1.getCountry() = Korea

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>/javainheritance/samples/MyPeopleExampleConstructorSuper2.  You can just open it and run it.

Summary

In this exercise,  you have learned how constructors of related classes are chained when an object instance is created.  You also learned how to use super() method in order to invoke a constructor of a parent class.

 

Exercise 3: Overriding method

In this exercise, you will exercise the concept of overriding method, which is probably the most important feature of Java inheritance.

  1. Override methods
  2. Runtime-polymorphism
  3. Hiding methods (applies only for static methods)

(3.1) Override methods

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyPeopleExampleOverriding, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumed you have created a new project.1. Modify Person.java as shown in Code-3.10 below.  The change is to add a new method myMethod(String t) that will be overridden by the sub class.  The code fragment that needs to be added is highlighted in bold and blue-colored font. The println methods in the constructors are commented out for the sake of simplicity.

package mypeopleexample;public class Person {

public Person() {
// System.out.println(“Person: constructor is called”);
}

public Person(String name) {
this.name = name;
// System.out.println(“Person: constructor 2 is called”);
}

protected String name;
protected String address;

public String getName() {
return name;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

// A method that will be overridden by sub-class
public void myMethod(String t){
System.out.println(“myMethod(” + t + “) in Person class”);
}

}

Code-3.10: Person.java

2. Modify Student.java as shown in Code-3.11 below.  The change is to change the access modifiers of the fields to protected so that they can be accessed from the sub class.  The code fragment that needs to be added is highlighted in bold and blue-colored font.  The println methods in the constructors are commented out for the sake of simplicity.

package mypeopleexample;public class Student extends Person {

public Student() {
// System.out.println(“Student: constructor is called”);
}

public Student(String name, String school, double grade) {
super(name);
this.school = school;
this.grade = grade;
// System.out.println(“Student: constructor 2 is called”);
}

protected String school;
protected double grade;

public String getSchool() {
return school;
}

public void setSchool(String school) {
this.school = school;
}

public double getGrade() {
return grade;
}

public void setGrade(double grade) {
this.grade = grade;
}

// A overriding method
public void myMethod(String t){
System.out.println(“myMethod(” + t + “) in Student class”);
}

}

Figure-3.11: Student.java with overriding method

3. Modify InternationalStudent.java as shown in Code-3.12 below.   The change is to change the access modifiers of the fields to protected so that they can be accessed from the sub class.  The code fragment that needs to be added is highlighted in bold and blue-colored font. The println methods in the constructors are commented out for the sake of simplicity.

package mypeopleexample;public class InternationalStudent extends Student {

public InternationalStudent() {
// System.out.println(“InternationalStudent: constructor is called”);
}

public InternationalStudent(String name, String school, double grade, String country) {
super.name = name;
super.school = school;
super.grade = grade;
this.country = country;
// System.out.println(“InternationalStudent: constructor 2 is called”);
}

private String country;

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

// A overriding method
public void myMethod(String t){
System.out.println(“myMethod(” + t + “) in InternationalStudent class”);
}

}

Code-3.12: InternationalStudent.java with overriding method

4. Modify Main.java as shown in Code-3.13 below.  The change is to create object instances of Person, Student, and InternationalStudent classes which are related through inheritance and invoke overridden myMethod() for each of these object instances.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Main {

public static void main(String[] args) {

System.out.println(“—- Observe overriding method behavior —-“);

Person person1 = new Person();
person1.myMethod(“test1”);

Student student1 = new Student();
student1.myMethod(“test2”);

InternationalStudent internationalStudent1 =
new InternationalStudent();
internationalStudent1.myMethod(“test3”);

}
}

Code-3.13: Main.java

5. Build and run the program.

  • Right click MyPeopleExampleOverriding and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-3.14 below)
—- Observe overriding behavior —-
myMethod(test1) in Person class
myMethod(test2) in Student class
myMethod(test3) in InternationalStudent class

Figure-3.14: 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>/javainheritance/samples/MyPeopleExampleOverriding.  You can just open it and run it.

(3.2) Runtime polymorphism

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyPeopleExampleOverridingPolymorphism, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumed you have created a new project.Note: This sample code does not meant to show the capability of runtime polymorphism but the underlying scheme that enables it.  The capability of polymorphic behavior will be explored again in another hands-on lab.

1. Modify Main.java as shown in Code-3.20 below.  The change is to observe runtime polymorphic behavior.  The code fragment that needs to be added is highlighted in bold and blue-colored font.

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

System.out.println(“—- Observe overriding method behavior —-“);

Person person1 = new Person();
person1.myMethod(“test1”);

Student student1 = new Student();
student1.myMethod(“test2”);

InternationalStudent internationalStudent1 =
new InternationalStudent();
internationalStudent1.myMethod(“test3”);

// Polymorphic behavior
System.out.println(“—- Observe polymorphic behavior —-“);

Person person2 = new Student();
person2.myMethod(“test4”);

Person person3 = new InternationalStudent();
person3.myMethod(“test5”);

Student student2 = new InternationalStudent();
student2.myMethod(“test6”);

}
}

Code-3.20: Main.java

2. Build and run the program.

  • Right click MyPeopleExampleOverridingPolymorphism and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-3.21 below)
—- Observe overriding behavior —-
myMethod(test1) in Person class
myMethod(test2) in Student class
myMethod(test3) in InternationalStudent class
—- Observe polymorphic behavior —-
myMethod(test4) in Student class
myMethod(test5) in InternationalStudent class
myMethod(test6) in InternationalStudent class

Figure-3.21: 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>/javainheritance/samples/MyPeopleExampleOverridingPolymorphism.  You can just open it and run it.

(3.3) Hide methods

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyPeopleExampleHidingMethods, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumed you have created a new project.1. Modify Person.java as shown in Code-3.30 below.  The change is to add a static method that will be hidden by the sub class. The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Person {

public Person() {
// System.out.println(“Person: constructor is called”);
}

public Person(String name) {
this.name = name;
// System.out.println(“Person: constructor 2 is called”);
}

protected String name;
protected String address;

public String getName() {
return name;
}

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

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

// A method that will be overridden by sub-class
public void myMethod(String t){
System.out.println(“myMethod(” + t + “) in Person class”);
}

// A method that will be hidden by sub-class
public static void myStaticMethod(String t){
System.out.println(“myStaticMethod(” + t + “) in Person class”);
}

}

Code-3.30: Person.java with a static method

2. Modify Student.java as shown in Code-3.31 below.  The change is to add a static method that will be hidden by the sub class. The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Student extends Person {

public Student() {
// System.out.println(“Student: constructor is called”);
}

public Student(String name, String school, double grade) {
super(name);
this.school = school;
this.grade = grade;
// System.out.println(“Student: constructor 2 is called”);
}

protected String school;
protected double grade;

public String getSchool() {
return school;
}

public void setSchool(String school) {
this.school = school;
}

public double getGrade() {
return grade;
}

public void setGrade(double grade) {
this.grade = grade;
}

// A overriding method
public void myMethod(String t){
System.out.println(“myMethod(” + t + “) in Student class”);
}

// A method that will be hidden by sub-class
public static void myStaticMethod(String t){
System.out.println(“myStaticMethod(” + t + “) in Student class”);
}
}

Code-3.31: Student.java with a static method

3. Modify InternationalStudent.java as shown in Code-3.32 below.  The change is to add a static method that will be hidden by the sub class.   The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class InternationalStudent extends Student {

public InternationalStudent() {
// System.out.println(“InternationalStudent: constructor is called”);
}

public InternationalStudent(String name, String school, double grade, String country) {
super.name = name;
super.school = school;
super.grade = grade;
this.country = country;
// System.out.println(“InternationalStudent: constructor 2 is called”);
}

private String country;

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

// A overriding method
public void myMethod(String t){
System.out.println(“myMethod(” + t + “) in InternationalStudent class”);
}

// A method that will be hidden by sub-class
public static void myStaticMethod(String t){
System.out.println(“myStaticMethod(” + t + “) in InternationalStudent class”);
}

}

Code-3.32: InternationalStudent.java with a static method

4. Modify Main.java as shown in Code-3.33 below.  The change is to call hiding method and observe that the static method of the type used is invoked.   The code fragment that needs to be added is highlighted in bold and blue-colored font.

package mypeopleexample;public class Main {

public static void main(String[] args) {

System.out.println(“—- Observe overriding behavior —-“);
Person person1 = new Person();
person1.myMethod(“test1”);

Student student1 = new Student();
student1.myMethod(“test2”);

InternationalStudent internationalStudent1 =
new InternationalStudent();
internationalStudent1.myMethod(“test3”);

// Polymorphic behavior
System.out.println(“—- Observe polymorphic behavior —-“);
Person person2 = new Student();
person2.myMethod(“test4”);

Person person3 = new InternationalStudent();
person3.myMethod(“test5”);

Student student2 = new InternationalStudent();
student2.myMethod(“test6”);

// Calling hiding methods
System.out.println(“—- Observe how calling hiding methods work —-“);
person2.myStaticMethod(“test7”);
person3.myStaticMethod(“test8”);
student2.myStaticMethod(“test9”);

}
}

Code-3.33: Main.java

5. Build and run the program.

  • Right click MyPeopleExampleHidingMethods and select Run.
  • Observe the result in the Output window of the NetBeans IDE paying special attention to the ones in bold font. (Figure-3.34 below)
—- Observe overriding behavior —-
myMethod(test1) in Person class
myMethod(test2) in Student class
myMethod(test3) in InternationalStudent class
—- Observe polymorphic behavior —-
myMethod(test4) in Student class
myMethod(test5) in InternationalStudent class
myMethod(test6) in InternationalStudent class
—- Observe how calling hiding methods work —-
myStaticMethod(test7) in Person class
myStaticMethod(test8) in Person class
myStaticMethod(test9) in Student class
Figure-3.34: ResultSolution: 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>/javainheritance/samples/MyPeopleExampleHidingMethods.  You can just open it and run it.

Exercise 4: Type casting

In this exercise, you will exercise type casting between types (classes) that are related through inheritance.

  1. Implicit type casting
  2. Explicit type casting with a runtime ClassCastException
  3. Explicit type casting without a runtime ClassCastException

(4.1) Implicit type casting

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyPeopleExampleImplicitCasting, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumed you have created a new project.

1. Modify the Main.java as shown in Code-4.11 below.  The change is to add a few more statements in which implicit type casting between types that are related are done.

package mypeopleexample;public class Main {

public static void main(String[] args) {

System.out.println(“—- Observe overriding behavior —-“);
Person person1 = new Person();
person1.myMethod(“test1”);

Student student1 = new Student();
student1.myMethod(“test2”);

InternationalStudent internationalStudent1 =
new InternationalStudent();
internationalStudent1.myMethod(“test3”);

// Polymorphic behavior
System.out.println(“—- Observe polymorphic behavior —-“);

// This is an implicit type casting between Student and Person class.
Person person2 = new Student();   // Example 1
person2 = student1;                        // Example 2
person2.myMethod(“test4”);

// This is an implicit type casting between InternationalStudent and Person class.
Person person3 = new InternationalStudent();   // Example 3
person3 =  internationalStudent1;                       // Example 4
person3.myMethod(“test5”);

// This is an implicit type casting between InternationalStudent and Student class.
Student student2 = new InternationalStudent();  // Example 5
student2 = internationalStudent1;                        // Example 6
student2.myMethod(“test6”);

// Calling hiding methods
System.out.println(“—- Observe how calling hiding methods work —-“);
person2.myStaticMethod(“test7”);
person3.myStaticMethod(“test8”);
student2.myStaticMethod(“test9”);

}
}

Code-4.11: Modified Main.java

 

2. Build and run the program

  • Right click MyPeopleExampleImplicitCasting project node and select Run.
  • Observe the result in the Output window of the NetBeans IDE. (Figure-4.12 below)
—- Observe overriding behavior —-
myMethod(test1) in Person class
myMethod(test2) in Student class
myMethod(test3) in InternationalStudent class
—- Observe polymorphic behavior —-
myMethod(test4) in Student class
myMethod(test5) in InternationalStudent class
myMethod(test6) in InternationalStudent class
—- Observe how calling hiding methods work —-
myStaticMethod(test7) in Person class
myStaticMethod(test8) in Person class
myStaticMethod(test9) in Student class

Figure-4.12: 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>/javainheritance/samples/MyPeopleExampleImplicitCasting.  You can just open it and run it.

(4.2) Explicit type casting with a runtime ClassCastException

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyTypeMismatchExampleProject1, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumed you have created a new project.1. Modify the Main.java as shown in Code-4.21 below.

package mytypemismatchexampleproject;public class Main {

public static void main(String[] args) {

// Implicit casting – Student object instance is
// type of Person.
Person person1 = new Student();

// Implicit casting – Teacher object instance is
// type of Person.
Person person2 = new Teacher();

// Explicit type casting.
Student student1 = (Student) person1;

// Explicit type casting – no compile error.
// But ClassCastException will occur during runtime.
Student student2 = (Student) person2;
}

}

Code-4.21: Explicit casting with a potental for runtime type mismatch exception

2. Build and run the program

  • Right click MyTypeMismatchExampleProject1 and select Run.
  • Observe that there is a java.lang.ClassCastException runtime exception.


Figure-4.22: java.lang.ClassCastException 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>/javainheritance/samples/MyTypeMismatchExampleProject1.  You can just open it and run it.

(4.3) Explicit type casting without ClassCastException

You can use the MyPeopleExample project for the change you are going to make in this step or you might want to create a new project, for example, MyTypeMismatchExampleProject2, by “copying” MyPeopleExample project – Right click MyPeopleExample project and select Copy Project.  This document assumed you have created a new project.
1. Modify the Main.java as shown in Code-4.23 below.  The code fragment that needs to be changed is highlighted in bold and blue-colored font.

package mytypemismatchexampleproject;public class Main {

public static void main(String[] args) {

// Implicit casting – Student object instance is
// type of Person.
Person person1 = new Student();

// Implicit casting – Teacher object instance is
// type of Person.
Person person2 = new Teacher();

// Explicit type casting.
Student student1 = (Student) person1;

// Do the casting only when the type is verified
if (person2 instanceof Student) {
Student student2 = (Student) person2;
System.out.println(“person2 instanceof Student = ” + true);
} else{
System.out.println(“person2 instanceof Student = ” + false);
}

}

}

Code-4.23: Use instanceOf operator to check the type of the object instance

2. Build and run the program.

  • Right click MyTypeMismatchExampleProject2 and select Run.
  • Observe the result in the Output window of the IDE.  (Figure-4.24 below)
person2 instanceof Student = false

Figure-4.24: 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>/javainheritance/samples/MyTypeMismatchExampleProject2.  You can just open it and run it.

Summary

In this exercise,  you learned how to do implicit and explicit casting between object instances that are related through inheritance.

Exercise 5: Final Class and Final Method

In this exercise, you will exercise the concept of final class and final method.

  1. Build and run a Java program with a final class
  2. Try to extend String class or Wrapper class
  3. Build and run a Java program with a final method

(5.1) Build and run a Java program with a final class

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 MyFinalClassExample.
  • Click Finish.
  • Observe that the MyFinalClassExample 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 Person.java.

  • 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 Person.
  • For the Package field, either enter myfinalclassexample or choose myfinalclassexample 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-5.10 below.  Note that the Person class is a final class, which means it cannot be extended.
package myfinalclassexample;// Make the Person class as a final class
public final class Person {

public Person() {
}

}

Code-5.10: Person.java as a final class

3. Write Teacher.java.

  • 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 Teacher.
  • For the Package field, either enter myfinalclassexample or choose myfinalclassexample from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Teacher.java gets displayed in the editor window.
  • Modify the IDE generated Teacher.java as shown in Code-5.11 below.  The change is to extend the Person class, which will result in a compile error.
package myfinalclassexample;/**
*
* @author sang
*/
public class Teacher extends Person{

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

}

Code-5.11: Teacher.java

4. Observe the compile error.  (Figure-5.12 below)


Figure-5.12: Observe the compile error

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>/javainheritance/samples/MyFinalClassExample.  You can just open it.

(5.2) Try to extend String class or Wrapper class

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 MyFinalClassExample2.
  • Click Finish.
  • Observe that the MyFinalClassExample2 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 Teacher.java.

  • 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 Teacher.
  • For the Package field, either enter myfinalclassexample2 or choose myfinalclassexample2 from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Teacher.java gets displayed in the editor window.
  • Modify the IDE generated Teacher.java as shown in Code-5.21 below.  The change is to extend the String class, which will result in a compile error.
package myfinalclassexample2;/**
*
* @author sang
*/
public class Teacher extends String{

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

}

Code-5.21: Teacher.java

3. Observe the compile error.
Figure-5.22: Observe the compile error

4. Display the Javadoc of the String class to verify that the String class is a final class.

  • Move your cursor to the String and right click Show Javadoc.
  • Observe the browser displayed with the Javadoc of String class.
  • Note that String class is a final class. (Figure-5.23 below)


Figure-5.23: Javadoc of String class, which is a final class

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>/javainheritance/samples/MyFinalClassExample2.  You can just open it.

return to top of the exercise

(5.3) Build and run a Java program with a final method

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 MyFinalMethodExample.
  • Click Finish.
  • Observe that the MyFinalMethodExample 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 Person.java.

  • Right click MyFinalMethodExample 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 Person.
  • For the Package field, either enter myfinalmethodexample or choose myfinalmethodexample 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-5.30 below.  Note that the Person class is a final class, which means it cannot be extended.
package myfinalmethodexample;public class Person {

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

// myMethod() is a final method
public final void myMethod(){
}
}

Code-5.30: Person.java has a final method

3. Write Teacher.java.

  • Right click MyFinalMethodExample 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 Teacher.
  • For the Package field, either enter  myfinalmethodexample or choose myfinalmethodexample from the drop-down menu.
  • Click Finish.
  • Observe that IDE generated Teacher.java gets displayed in the editor window.
  • Modify the IDE generated Teacher.java as shown in Code-5.31 below.  The change is to make Teacher class to extend Person and and then to override the myMethod() of the Person class, which will result in a compile error.
package myfinalmethodexample;public class Teacher extends Person{

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

// Try to override this method
public void myMethod(){
}

}

Code-5.31: Teacher.java

4. Observe the compile error. (Figure-5.32 below)


Figure-5.32: Compile error

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>/javainheritance/samples/MyFinalMethodExample.  You can just open it.

Summary

In this exercise,  you learned that a final class cannot be extended and a final method cannot be overridden by a sub-class.

 

Exercise 6: Build a simple program using Inheritance

In this exercise, you will build a simple program using several classes that are related through Inheritance.  The Product class is sub-class’ed by Electronics and Book class. The Electronics class is further sub-classed by MP3Player and TV class.  You will also learn how to add polymorphic behavior to the program through method overriding.

  1. Build MyOnlineShop program

(6.1) Build MyOnlineShop program

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 MyOnlineShop.
  • Click Finish.
  • Observe that the MyOnlineShop 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.

  • 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 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-6.10 below.
package myonlineshop;public class Product {

private double regularPrice;

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

// Method that will be overridden
public double computeSalePrice(){
return 0;
}

public double getRegularPrice() {
return regularPrice;
}

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

}

Code-6.10: Product.java

3. Write Electronics.java.

  • 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-6.11 below.  Note that Electronics class extends Product class.
package myonlineshop;public class Electronics extends Product{

private String manufacturer;

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

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

public String getManufacturer() {
return manufacturer;
}

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

}

Code-6.11: Electronics.java

4. Write MP3Player.java.

  • 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-6.12 below.  Note that MP3Player class extends Electronics class.  Note also that the MP3Player class has computeSalePrice() method which is an overriding method.
package myonlineshop;public class MP3Player extends Electronics{

private String color;

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

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

public String getColor() {
return color;
}

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

Code-6.12: MP3Player.java

5. Write TV.java.

  • 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-6.14 below.  Note that TV class extends Electronics class.  Note also that the TV class has computeSalePrice() method which is an overriding method.
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;
}

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

Code-6.14: TV.java

6. Write Book.java.

  • 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-6.15 below.  Note that Book class extends Product class.  Note also that the Book class has computeSalePrice() method which is an overriding method.
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;
}

// Override this 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-6.15: Book.java

7. Modify Main.java as shown in Code-6.16 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
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
// 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-6.16: Main.java

8. Build and run the program.

  • Right click MyOnlineShop and select Run.
  • Observe the result in the Output window of the IDE.  (Figure-6.17 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-6.17: 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>/javainheritance/samples/MyOnlineShop.  You can just open it and run it.

9. For your own exercise 1, modify the MyOnlineShop as following:

  • Add Camera class which is a sub-class of Eletronics class
  • Compute the sale price of Camera with the following business logic
    • Regular price * 0.7
  • In the Main.java, initialize two object instances of Camera class

10. For your own exercise 2, modify the MyOnlineShop as following:

  • Add another overriding method to the classes like following
    • double computeSpecialCustomerPrice()
    • The computation logic should be as following:
      • For TV, subtract 100 from the sale price
      • For MP3Player, substract 15 from the sale price
      • For Book, subtract 2 from the sale price
  • In the Main.java, display Special Customer Price for each product iteam

Summary

In this exercise, you will build a simple program using several classes that are related through Inheritance.  You also built a polymorphic behavior through overloading methods.

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

 

1. The homework is to create a new NetBeans project called “MyOwnAutoShopProject” as following:
  • Create a super class called Car.  The Car class has the following fields and methods.
    • int speed;
    • double regularPrice;
    • String color;
    • double getSalePrice();
  • Create a subclass of Car class and name it as Truck.  The Truck class has the following fields and methods.
    • int weight;
    • double getSalePrice();  // If weight > 2000, 10% discount. Otherwise, 20% discount.
  • Create a subclass of Car class and name it as Ford.  The Ford class has the following fields and methods
    • int year;
    • int manufacturerDiscount;
    • double getSalePrice();  // From the sale price computed from Car class, subtract the manufacturerDiscount.
  • Create a subclass of Car class and name it as Sedan. The Sedan class has the following fields and methods.
    • int length;
    • double getSalePrice();  // If length > 20 feet, 5% discount, Otherwise, 10% discount.
  • Create MyOwnAutoShop class which contains the main() method.  Perform the following within the main() method.
    • Create an instance of Sedan class and initialize all the fields with appropriate values.  Use super(…) method in the constructor for initializing the fields of the super class.
    • Create two instances of the Ford class and initialize all the fields with appropriate values.  Use super(…) method in the constructor for initializing the fields of the super class.
    • Create an instance of Car class and and initialize all the fields with appropriate values.
  • Display the sale prices of all instance.
2. Send the following files to javaprogramminghomework@sun.com with Subject as JavaIntro-javainheritance.
  • Zip file of the the MyOwnAutoShopProject 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 MyOwnAutoShopProject directory> (assuming you named your project as MyOwnAutoShopProject)
    • jar cvf MyOwnAutoShopProject.zip MyOwnAutoShopProject (MyOwnAutoShopProject should contain nbproject directory)
  • Captured output screen  – name it as JavaIntro-javainheritance.gif orJavaIntro-javainheritance.jpg (or JavaIntro-javainheritance.<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.

 

 

답글 남기기

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

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