Lab Exercises
- Exercise 1: Build and run a Java program which uses classes that are related through Inheritance (30 minutes)
- Exercise 2: Constructor calling chain and super keyword (30 minutes)
- Exercise 3: Overloading (30 minutes)
- Exercise 4: Type casting (30 minutes)
- Exercise 5: Final class and final method (20 minutes)
- Exercise 6: Build an application (30 minutes)
- Homework Exercise (for people who are taking Sang Shin’s “Java Programming online course”)
Exercise 1: Build and run a Java program which uses classes that are related through Inheritance
(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; public String getName() { public void setName(String name) { public String getAddress() { public void setAddress(String 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; public String getSchool() { public void setSchool(String school) { public double getGrade() { public void setGrade(double 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 */ private String country; public String getCountry() { public void setCountry(String 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() { public void setSubject(String 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. Person person1 = new Person(); Student student1 = new Student(); InternationalStudent internationalStudent1 = Teacher teacher1 = new Teacher(); // Display name of object instances using the getName() method } |
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
package mypeopleexample;public class Main {
public static void main(String[] args) { // Create object instances and invoke methods. Person person1 = new Person(); Student student1 = new Student(); InternationalStudent internationalStudent1 = Teacher teacher1 = new Teacher(); // Display name of object instances using the getName() method // Display the class hierarchy of the InternationalStudent System.out.println(“Displaying class hierarchy of InternationalStudent Class…”); |
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
package mypeopleexample;public class Person {
public Person() { private String name; public String getName() { public void setName(String name) { public String getAddress() { public void setAddress(String 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() { private String school; public String getSchool() { public void setSchool(String school) { public double getGrade() { public void setGrade(double 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() { private String country; public String getCountry() { public void setCountry(String 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() { private String subject; public String getSubject() { public void setSubject(String 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 // Create an object instance of } |
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
package mypeopleexample;public class Person {
public Person() { public Person(String name) { private String name; public String getName() { public void setName(String name) { public String getAddress() { public void setAddress(String 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() { public Student(String name, String school, double grade) { private String school; public String getSchool() { public void setSchool(String school) { public double getGrade() { public void setGrade(double 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() { public InternationalStudent(String name, String school, double grade, String country) { private String country; public String getCountry() { public void setCountry(String 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 System.out.println(“internationalStudent1.getName() = ” + internationalStudent1.getName()); |
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
package mypeopleexample;public class Person {
public Person() { public Person(String name) { protected String name; public String getName() { public void setName(String name) { public String getAddress() { public void setAddress(String 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() { public Student(String name, String school, double grade) { protected String school; public String getSchool() { public void setSchool(String school) { public double getGrade() { public void setGrade(double 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() { public InternationalStudent(String name, String school, double grade, String country) { private String country; public String getCountry() { public void setCountry(String 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
- Override methods
- Runtime-polymorphism
- Hiding methods (applies only for static methods)
(3.1) Override methods
package mypeopleexample;public class Person {
public Person() { public Person(String name) { protected String name; public String getName() { public void setName(String name) { public String getAddress() { public void setAddress(String address) { // A method that will be overridden by sub-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() { public Student(String name, String school, double grade) { protected String school; public String getSchool() { public void setSchool(String school) { public double getGrade() { public void setGrade(double grade) { // A overriding method } |
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() { public InternationalStudent(String name, String school, double grade, String country) { private String country; public String getCountry() { public void setCountry(String country) { // A overriding method } |
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(); Student student1 = new Student(); InternationalStudent internationalStudent1 = } |
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
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(); Student student1 = new Student(); InternationalStudent internationalStudent1 = // Polymorphic behavior Person person2 = new Student(); Person person3 = new InternationalStudent(); Student student2 = new InternationalStudent(); } |
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
package mypeopleexample;public class Person {
public Person() { public Person(String name) { protected String name; public String getName() { public void setName(String name) { public String getAddress() { public void setAddress(String address) { // A method that will be overridden by sub-class // A method that will be hidden by sub-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() { public Student(String name, String school, double grade) { protected String school; public String getSchool() { public void setSchool(String school) { public double getGrade() { public void setGrade(double grade) { // A overriding method // A method that will be hidden by sub-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() { public InternationalStudent(String name, String school, double grade, String country) { private String country; public String getCountry() { public void setCountry(String country) { // A overriding method // A method that will be hidden by sub-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 —-“); Student student1 = new Student(); InternationalStudent internationalStudent1 = // Polymorphic behavior Person person3 = new InternationalStudent(); Student student2 = new InternationalStudent(); // Calling hiding methods } |
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 |
Exercise 4: Type casting
- Implicit type casting
- Explicit type casting with a runtime ClassCastException
- 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 —-“); Student student1 = new Student(); InternationalStudent internationalStudent1 = // Polymorphic behavior // This is an implicit type casting between Student and Person class. // This is an implicit type casting between InternationalStudent and Person class. // This is an implicit type casting between InternationalStudent and Student class. // Calling hiding methods } |
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
package mytypemismatchexampleproject;public class Main {
public static void main(String[] args) { // Implicit casting – Student object instance is // Implicit casting – Teacher object instance is // Explicit type casting. // Explicit type casting – no compile error. } |
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
(4.3) Explicit type casting without ClassCastException
package mytypemismatchexampleproject;public class Main {
public static void main(String[] args) { // Implicit casting – Student object instance is // Implicit casting – Teacher object instance is // Explicit type casting. // Do the casting only when the type is verified } } |
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.
- Build and run a Java program with a final class
- Try to extend String class or Wrapper class
- 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 */ } |
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 */ } |
Code-5.21: Teacher.java
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.
(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 */ // myMethod() is a final method |
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 */ // Try to override this method } |
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
(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 */ // Method that will be overridden public double getRegularPrice() { public void setRegularPrice(double 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 */ // Override this method public String getManufacturer() { public void setManufacturer(String 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; /** // Override this method public String getColor() { public void setColor(String 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 */ // Override this method |
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; /** Creates a new instance of Book */ // Override this method public String getPublisher() { public void setPublisher(String publisher) { public int getYearPublished() { public void setYearPublished(int 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 // Create object instances // Compute total regular price and total for (int i=0; i<pa.length; i++){ // Call a method of the super class to get // Since the sale price is computed differently System.out.println(“Item number ” + i + } |
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”)
- 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.
- 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.