Lab Exercises
- Exercise 1: Abstract class (30 minutes)
- Exercise 2: Interface as a Type (30 minutes)
- Exercise 3: Implementing multiple interfaces (30 minutes)
- Exercise 4: Interface and polymorphism (20 minutes)
- Exercise 5: Inheritance among interfaces (30 minutes)
- Exercise 6: Rewriting an interface (20 minutes)
- Homework Exercise (for people who are taking Sang Shin’s “Java Programming online course”)
Exercise 1: Abstract class
In this exercise, you will write Java program that use abstract classes. You will also learn how to add polymorphic behavior to the program through abstact methods.
(1.1) Build and run an application that uses an Abstract class
0. Start NetBeans IDE if you have not done so.
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyAbstractClassProject. (Figure-1.10 below)
- Click Finish.
Figure-1.10: Create a project
- Observe that the MyAbstractClassProject project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.
2. Write LivingThing.java as an abstract class.
- Right click MyAbstractClassProject project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter LivingThing.
- For the Package field, either enter myabstractclassproject or choose myabstractclassprojectfrom the drop-down menu. (Figure-1.11 below)
- Click Finish.
Figure-1.11: Write LivingThing abstract class
- Observe that IDE generated LivingThing.java gets displayed in the editor window.
- Modify the IDE generated LivingThing.java as shown in Code-1.12 below.
- Study the code by paying special attention to bold-fonted part.
package myabstractclassproject;// The LivingThing class is an abstract class because // some methods in it are declared as abstract methods. public abstract class LivingThing { private String name; public LivingThing(String name){ public void breath(){ public void eat(){ /** public String getName() { public void setName(String name) { |
Code-1.12: LivingThing.java
3. Write Human.java. The Human.java is a concrete class that extends the LivingThing abstract class.
- Right click MyAbstractClassProject project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Human.
- For the Package field, either enter myabstractclassproject or choose myabstractclassprojectfrom the drop-down menu.
- Click Finish.
- Observe that IDE generated Human.java gets displayed in the editor window.
- Modify the IDE generated Human.java as shown in Code-1.13 below.
- Study the code by paying special attention to bold-fonted part.
package myabstractclassproject;public class Human extends LivingThing {
public Human(String name){ // Provide implementation of the abstract method. } |
Code-1.13: Human.java
4. Write Monkey.java. (Code-1.14 below)
package myabstractclassproject;public class Monkey extends LivingThing {
public Monkey(String name){ // Implement the abstract method |
Code-1.14: Monkey.java
5. Modify Main.java as shown in Code-1.15 below. Study the code by paying special attention to bold-fonted part.
package myabstractclassproject;public class Main {
public static void main(String[] args) { // Create Human object instance // Create Human object instance // Create a Monkey object instance // Display data from human1 and livingthing1. // Check of object instance that is referred by x and // Compile error } |
Code-1.15: Main.java
6. Build and run the program.
- Right click MyAbstractClassProject and select Run.
- Observe the result is displayed in the Outout window of the IDE. (Figure-1.16 below)
Human Sang Shin walks… Human Sang Shin walks… Monkey MonkeyWrench also walks… human1.getName() = Sang Shin livingthing1.getName() = Sang Shin Do human1 and livingthing1 point to the same object instance? true |
Figure-1.16: Result
7. For your own exercise, please do the following:
- Define another abstract method in the LivingThing.java as following
- public abstract void dance(String dancingStyle);
- Implement a concrete method in the Human.java and Monkey.java
- Modify Main.java to invoke dance(String dancingStyle) method through obect instances of human1 and livingthing1.
- Example dancing styles could be Tango, ChaChaCha, or whatever
Solution: The solution to this exercise is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyAbstractClassProject. You can just open it and run it.
(1.2) Build MyOnlineShopUsingAbstractClass program
In this step, you are going to rewrite MyOnlineShop program you built and run in the Java Inheritance hands-on lab to use an abstract method of an abstract class (instead of overriding method of a concrete class). The differences are highlighted in bold font.
The MyOnlineShop project is provided as part of this hands-on lab zip file for your convenience. You can open it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyOnlineShop. The instruction below is written with an assumption that you are stating from scratch.
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Observe that the Name and Location pane appears.
- For the Project Name field, enter MyOnlineShopUsingAbstractClass.
- Click Finish.
- Observe that the MyOnlineShopUsingAbstractClass project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.
2. Write Product.java. The Product class is an abstract class that has an abstract method called computeSalePrice().
- Right click MyOnlineShopUsingAbstractClass project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Product.
- For the Package field, either enter myonlineshop or choose myonlineshopfrom the drop-down menu.
- Click Finish.
- Observe that IDE generated Product.java gets displayed in the editor window.
- Modify the IDE generated Product.java as shown in Code-1.20 below.
package myonlineshop;// Product class is now an abstract class public abstract class Product { private double regularPrice; /** Creates a new instance of Product */ // computeSalePrice() is now an abstract method public double getRegularPrice() { public void setRegularPrice(double regularPrice) { } |
Code-1.20: Product.java
3. Write Electronics.java. The Electronics class itself is an abstract class because it does not provide implementation of the computeSalePrice() abstract method.
- Right click MyFinalClassExample project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Electronics.
- For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
- Click Finish.
- Observe that IDE generated Electronics.java gets displayed in the editor window.
- Modify the IDE generated Electronics.java as shown in Code-1.21 below. Note that Electronics class extends Product class.
package myonlineshop;// Electronics class is now an abstract class because // it does not provide implementation of the // computeSalePrice() abstract method. public abstract class Electronics extends Product{ private String manufacturer; /** Creates a new instance of Electronics */ public String getManufacturer() { public void setManufacturer(String manufacturer) { } |
Code-1.21: Electronics.java
4. Write MP3Player.java. The MP3Player class extends Electronics class. Note also that the MP3Player class has implementation of the computeSalePrice() method.
- Right click MyFinalClassExample project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter MP3Player.
- For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
- Click Finish.
- Observe that IDE generated MP3Player.java gets displayed in the editor window.
- Modify the IDE generated MP3Player.java as shown in Code-1.23 below.
package myonlineshop;public class MP3Player extends Electronics{
private String color; public MP3Player(double regularPrice, // Implement the abstract method public String getColor() { public void setColor(String color) { |
Code-1.23: MP3Player.java
5. Write TV.java. The TV class extends Electronics abstract class. Note also that the TV class has the implementation of the computeSalePrice() method.
- Right click MyFinalClassExample project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter TV.
- For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
- Click Finish.
- Observe that IDE generated TV.java gets displayed in the editor window.
- Modify the IDE generated TV.java as shown in Code-1.24 below.
package myonlineshop;public class TV extends Electronics {
int size; /** Creates a new instance of TV */ // Implement the abstract method |
Code-1.24: TV.java
6. Write Book.java. The Book class extends Product class. Note also that the Book class has the implementation of the computeSalePrice() method.
- Right click MyFinalClassExample project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Book.
- For the Package field, either enter myonlineshop or choose myonlineshop from the drop-down menu.
- Click Finish.
- Observe that IDE generated Book.java gets displayed in the editor window.
- Modify the IDE generated Book.java as shown in Code-1.25 below.
package myonlineshop;public class Book extends Product{
private String publisher; /** Creates a new instance of Book */ // Implement the abstract method public String getPublisher() { public void setPublisher(String publisher) { public int getYearPublished() { public void setYearPublished(int yearPublished) { } |
Code-1.25: Book.java
7. Modify Main.java as shown in Code-1.26 below. Study the code by special attention to the bold fonted comments,
package myonlineshop;public class Main {
public static void main(String[] args) { // Declare and create Product array of size 5 // Create object instances and assign them to // 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-1.26: Main.java
8. Build and run the program.
- Right click MyOnlineShopUsingAbstractClass and select Run.
- Observe the result in the Output window of the IDE. (Figure-1.27 below)
Item number 0: Type = myonlineshop.TV, Regular price = 1000.0, Sale price = 800.0 Item number 1: Type = myonlineshop.TV, Regular price = 2000.0, Sale price = 1600.0 Item number 2: Type = myonlineshop.MP3Player, Regular price = 250.0, Sale price = 225.0 Item number 3: Type = myonlineshop.Book, Regular price = 34.0, Sale price = 17.0 Item number 4: Type = myonlineshop.Book, Regular price = 15.0, Sale price = 7.5 totalRegularPrice = 3299.0 totalSalePrice = 2649.5 |
Figure-1.27: Result
Solution: The solution to this step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyOnlineShopUsingAbstractClass. You can just open it and run it.
Summary
In this exercise, you will build a simple program using an abstract class. You also learned how to add polymorphic behavior to the program using abstract methods.
Exercise 2: Java Interface as a Type
In this exercise, you will build a simple Java application that uses Interface as a type.
(2.1) Build a Java program that uses Interface as a type
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyPersonInterface. (Figure-2.10 below)
- Click Finish.
Figure-2.10: Create MyPersonInterfaceProject
- Observe that the MyPersonInterfaceProject project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.
- Right click MyPersonInterfaceProject project node and select New->Java Class. (You can choose New->Java Interface as well.)
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter PersonInterface.
- For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu. (Figure-2.11 below)
- Click Finish.
Figure-2.11: PersonInterface interface
- Observe that IDE generated PersonInterface.java gets displayed in the editor window.
- Modify the IDE generated PersonInterface.java as shown in Code-2.12 below.
package mypersoninterfaceproject;public interface PersonInterface {
// Compute person’s total wealth // Get person’s name } |
Code-2.12: PersonInterface.java
3. Write Person.java. The Person class implements PersonInterface interface.
- Right click MyPersonInterfaceProjectproject node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Person.
- For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.
- Click Finish.
- Observe that IDE generated Person.java gets displayed in the editor window.
- Modify the IDE generated Person.java as shown in Code-2.13 below.
- Study the code by paying special attention to bold-fonted part.
package mypersoninterfaceproject;public class Person implements PersonInterface {
int cashSaving; // Constructor with arguments // Compute person’s total wealth // Get person’s name } |
Code-2.13: Person.java
4. Modify Main.java as shown in Code-2.14 below. Study the code paying special attention to the bold-fonted part.
package mypersoninterfaceproject;public class Main {
public static void main(String[] args) { // Create an object instance of Person class. // You can assign the object instance to // Display data from person1 and personinterface1. System.out.println(“personinterface1.getName() = ” + personinterface1.getName() + “,” + // Check of object instance that is referred by person1 and // Create an object instance of Person class System.out.println(“personinterface2.getName() = ” + personinterface2.getName() + “,” + } } |
Code-2.14: Main.java
5. Build and run the program.
- Right click MyPersonInterfaceProject and select Run.
- Observe the result in the Output window of the IDE. (Figure-2.15 below)
30000 person1.getName() = Sang Shin, person1.computeTotalWealth() = 30000 30000 personinterface1.getName() = Sang Shin, personinterface1.computeTotalWealth() = 30000 Do person1 and personinterface1 point to the same object instance? true 7000 personinterface2.getName() = Dadu Daniel, personinterface2.computeTotalWealth() = 7000 |
Figure-2.15: Result
Solution: The solution to this step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyPersonInterfaceProject. You can just open it and run it.
(2.2) Build a Java program that uses RelationInterface Interface
In this step, you are going to build another Java program that uses a Java interface called RelationInterface.
1. Create a NetBeans project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyRelationInterfaceProject.
- Click Finish.
- Observe that the MyRelationInterfaceProject project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.
2. Write RelationInterface Java interface.
- Right click MyPersonInterfaceProject project node and select New->Java Class. (You can choose New->Java Interface as well.)
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter RelationInterface.
- For the Package field, either enter myrelationinterfaceproject or choose myrelationinterfaceproject from the drop-down menu.
- Click Finish.
- Observe that IDE generated RelationInterface.java gets displayed in the editor window.
- Modify the IDE generated RelationInterface.java as shown in Code-2.21 below.
package myrelationinterfaceproject;// Define an interface with three abstract methods. // Any class that implements this interface has to // implement all three methods. public interface RelationInterface { public boolean isGreater( Object a, Object b); public boolean isLess( Object a, Object b); public boolean isEqual( Object a, Object b); } |
Code-2.21: RelationInterface.java
- Right click MyPersonInterfaceProjectproject node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Line.
- For the Package field, either enter myrelationinterfaceproject or choose myrelationinterfaceproject from the drop-down menu.
- Click Finish.
- Observe that IDE generated Line.java gets displayed in the editor window.
- Modify the IDE generated Line.java as shown in Code-2.23 below.
package myrelationinterfaceproject;public class Line implements RelationInterface{
private double x1; // Constructor methoe of the Line class. // A new method definition of the Line class // Implement isGreater(..) method defined in the Relation interface // Implement isLess(..) method defined in the Relation interface // Implement isEqual(..) method defined in the Relation interface } |
Code-2.23: Line.java
4. Modify Main.java as shown in Code-2.24 below. Study the code paying special attention to the bold-fonted part.
package myrelationinterfaceproject;public class Main {
public static void main(String[] args) { // Create two Line object instances. boolean b1 = line1.isGreater(line1, line2); // Note that the line3 is object instance of Line type. System.out.println(“Length of line1 is ” + line1.getLength()); // The following line of code will generate a compile error since line3 } |
Code-2.24: Main.java
5. Build and run the program
- Right click MyRelationInterfaceProject and select Run.
- Observe the result in the Output window of the IDE. (Figure-2.25 below)
line1 is greater than line2: false line1 is equal with line2: true line1 is equal with line3: false Length of line1 is 1.4142135623730951 Length of line2 is 1.4142135623730951 |
Figure-2.25: Result
6. For your own exercise, do the following.
- Uncomment the last commented line of the Main.java that contains line3.getLength() and observe the compile error.
- Understand why the compiler error occurs.
Solution: The solution to this step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyRelationInterfaceProject. You can just open it and run it.
Summary
In this exercise, you built two Java programs which use Java interface. You learned how a Java interface is used as a type. You learned how a concrete class implements a Java interface.
Exercise 3: Implementing multiple Interfaces
In this exercise, you are going to learn a how a concrete class can implement multiple Java interfaces.
(3.1) Build and run a Java program that uses multiple Java interfaces
- Right click MyPersonInterfaceProject project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter AnotherInterfaceExample
- For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.
- Click Finish.
- Observe that IDE generated AnotherInterfceExample.java gets displayed in the editor window.
- Modify the IDE generated AnotherInterfceExample.java as shown in Code-3.10 below.
package mypersoninterfaceproject;public interface AnotherInterfaceExample {
// Measure person’s intelligence } |
Code-3.10: AnotherInterfaceExample.java
2. Modify Person.java as shown in Code-3.11 below. The change is to have the Person class to implement the AnotherInterfaceExample interface in addition to PersonInterface interface. The code fragments that need to be added are highlighted in bold and blue-colored font.
package mypersoninterfaceproject;public class Person implements PersonInterface, AnotherInterfaceExample{ int cashSaving; // Constructor with arguments // Compute person’s total wealth // Get person’s name // Implement method of AnotherInterfaceExample } |
Code-3.11: Modified Person.java
3. Modify Main.java as shown in Code-3.12 below. The change is to show that now the object instance of the Person class now can invoke the method defined in the new interface. The code fragments that need to be changed are highlighted in bold and blue-colored font.
package mypersoninterfaceproject; public class Main {public static void main(String[] args) { // Create an object instance of Person class. // You can assign the object instance to // Display data from person1 and personinterface1. System.out.println(“personinterface1.getName() = ” + personinterface1.getName() + “,” + // Compile error is expected on the following line of code. // You can assign the object instance to // Check of object instance that is referred by personinterface1 and } } |
Code-3.12: Modified Main.java
4. Build and run the program.
- Right click MyPersonMultipleInterfaces and select Run.
- Observe the result in the Output window of the IDE.
30000 person1.getName() = Sang Shin, person1.computeTotalWealth() = 30000, person1.measureIntelligence() = 50 30000 personinterface1.getName() = Sang Shin, personinterface1.computeTotalWealth() = 30000 Do personinterface1 and anotherinterfaceexample1 point to the same object instance? true |
Code-3.13: Result
Solution: The solution to this step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyPersonMultipleInterfaces. You can just open it and run it.
5. For your own exercise, please do the following:
- Add the 3rd interface with the following mtehod
- int computeFirstNameLength(String name);
- Make the Person class to implement the 3rd interface
- The implementation of the computeFirstNameLength(String name) returns the length of the first name
- Modify Main.java to display information accordingly
Summary
In this exercise, you have reimplemented MyPersonInterfaceProject to have the Person class to implement multiple Java interfaces.
Exercise 4: Inheritance and polymorphism
In this exercise, you are going to rewrite MyOnlineShopUsingAbstractClass program you built above to use Java interface (instead of Abstract class).
(4.1) Build MyOnlineShopUsingInterface project
- Select File from top-level menu and select New Project.
- Observe that the New Project dialog box appears.
- Select Java under Categories section and Java Application under Projects section.
- Click Next.
- Under Name and Location pane, for the Project Name field, enter MyOnlineShopUsingInterface. (Figure-1.10 below)
- Click Finish.
- Observe that the MyOnlineShopUsingInterface project node is created under Projects pane of the NetBeans IDE and IDE generated Main.java is displayed in the editor window of the IDE.
- Right click MyOnlineShopUsingInterface project node and select New->Java Class. (You can choose New->Java Interface)
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter ProductInterface.
- For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
- Click Finish.
- Observe that IDE generated ProductInterface.java gets displayed in the editor window.
- Modify the IDE generated ProductInterface.java as shown in Code-4.11 below.
package myonlineshopusinginterface;public interface ProductInterface { public double computeSalePrice(); public double getRegularPrice(); public void setRegularPrice(double regularPrice); } |
Code-4.11: ProductInterface.java
3. Write Product.java.
- Right click MyOnlineShopUsingInterface project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Product.
- For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
- Click Finish.
- Observe that IDE generated Product.java gets displayed in the editor window.
- Modify the IDE generated Product.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class Product implements ProductInterface{
private double regularPrice; /** Creates a new instance of Product */ // Implement the methods of the ProductInterface public double getRegularPrice() { public void setRegularPrice(double regularPrice) { } |
Code-4.12: Product.java
- Right click MyOnlineShopUsingInterface project node and select New->Java Class. (You can choose New->Java Interface)
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter ElectronicsInterface.
- For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
- Click Finish.
- Observe that IDE generate ElectronicsInterface.java gets displayed in the editor window.
- Modify the IDE generated ElectronicsInteface.java as shown in Code-4.13 below.
package myonlineshopusinginterface;public interface ElectronicsInterface extends ProductInterface {
public String getManufacturer(); } |
Code-4.12: ElectronicsInterface.java
5. Write Electronics.java.
- Right click MyOnlineShopUsingInterface project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Electronics.
- For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
- Click Finish.
- Observe that IDE generated Electronics.java gets displayed in the editor window.
- Modify the IDE generated Electronics.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class Electronics extends Product implements ElectronicsInterface {
private String manufacturer; /** Creates a new instance of Electronics */ public String getManufacturer() { public void setManufacturer(String manufacturer) { |
Code-4.12: Electronics.java
6. Write MP3Player.java.
- Right click MyOnlineShopUsingInterface project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter MP3Player.
- For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
- Click Finish.
- Observe that IDE generated MP3Player.java gets displayed in the editor window.
- Modify the IDE generated MP3Player.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class MP3Player extends Electronics{
private String color; public MP3Player(double regularPrice, // Override the method public String getColor() { public void setColor(String color) { |
Code-4.12: MP3Player.java
7. Write TV.java.
- Right click MyOnlineShopUsingInterface project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter TV.
- For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
- Click Finish.
- Observe that IDE generated TV.java gets displayed in the editor window.
- Modify the IDE generated TV.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class TV extends Electronics {
int size; /** Creates a new instance of TV */ // Override the method |
Code-4.12: TV.java
8. Write Book.java.
- Right click MyOnlineShopUsingInterface project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Book.
- For the Package field, either enter myonlineshopusinginterface or choose myonlineshopusinginterface from the drop-down menu.
- Click Finish.
- Observe that IDE generated Book.java gets displayed in the editor window.
- Modify the IDE generated Book.java as shown in Code-4.12 below.
package myonlineshopusinginterface;public class Book extends Product {
private String publisher; /** Creates a new instance of Book */ // Override the method public String getPublisher() { public void setPublisher(String publisher) { public int getYearPublished() { public void setYearPublished(int yearPublished) { } |
Code-4.12: Book.java
9. Modify Main.java as shown in Code-3.12 below.
package myonlineshopusinginterface;public class Main {
/** Creates a new instance of Main */ public static void main(String[] args) { // Declare and create Product array of size 5 // Create object instances and assign them to // 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-3.12: Modified Main.java
4. Build and run the program
- Right click MyOnlineShopUsingInterface and select Run.
- Observe the result in the Output window of the IDE.
Item number 0: Type = myonlineshopusinginterface.TV, Regular price = 1000.0, Sale price = 800.0 Item number 1: Type = myonlineshopusinginterface.TV, Regular price = 2000.0, Sale price = 1600.0 Item number 2: Type = myonlineshopusinginterface.MP3Player, Regular price = 250.0, Sale price = 225.0 Item number 3: Type = myonlineshopusinginterface.Book, Regular price = 34.0, Sale price = 17.0 Item number 4: Type = myonlineshopusinginterface.Book, Regular price = 15.0, Sale price = 7.5 totalRegularPrice = 3299.0 totalSalePrice = 2649.5 |
Code-3.13: Result
Solution: The solution to this step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyOnlineShopUsingInterface. You can just open it and run it.
Summary
In this exercise, you have rewritten MyOnlineShop application using Java interfaces.
Exercise 5: Inheritance among Interfaces
Interfaces can have inheritance relationship among themselves.
(5.1) Build and run a Java program that uses Java interfaces that are related through inheritance
- Right click MyPersonInheritanceInterfacesproject node and select New->Java Class. (You can choose New->Java Interface as well.)
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter StudentInterface
- For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.
- Click Finish.
- Observe that IDE generated StudentInterface.java gets displayed in the editor window.
- Modify the IDE generated StudentInterface.java as shown in Code-5.10 below.
- Study the code by paying attention to the bold-fonted part.
package mypersoninterfaceproject;// StudentInterface interface extends PersonInteface interface public interface StudentInterface extends PersonInterface{ // Find the school the student attends } |
Code-5.10: StudentInterface.java
2. Write Student.java. The Student class implements StudentInterface interface. The Student class implements all the methods defined in the StudentInterface interface and its parent interfaces.
- Right click MyOnlineShopUsingAbstractClass project node and select New->Java Class.
- Observe Name and Location pane of the New Java Class dialog box appears.
- For the Class Name field, enter Student.
- For the Package field, either enter mypersoninterfaceproject or choose mypersoninterfaceproject from the drop-down menu.
- Click Finish.
- Observe that IDE generated Student.java gets displayed in the editor window.
- Modify the IDE generated Student.java as shown in Code-5.11 below.
package mypersoninterfaceproject;public class Student implements StudentInterface {
int cashSaving; // Constructor with arguments // Compute person’s total wealth // Get person’s name // Find out the school the student attends |
Code-5.11: Modified Student.java
3. Modify Main.java as shown in Code-5.12 below
package mypersoninterfaceproject;public class Main {
public static void main(String[] args) { // Create an object instance of Student class. // You can assign the object instance to // Display data from student1 and studentinterface1. System.out.println(“studentinterface1.getName() = ” + studentinterface1.getName() + “,” + // Check of object instance that is referred by student1 and } } |
Code-5.12: Modified Main.java
4. Build and run the program
- Right click MyPersonInheritanceInterfaces and select Run.
- Observe the result in the Output window of the IDE. (Figure-5.13 below)
30000 student1.getName() = Sang Shin, student1.computeTotalWealth() = 30000, student1.findSchool() = Good School 30000 studentinterface1.getName() = Sang Shin, studentinterface1.computeTotalWealth() = 30000, studentinterface1.findSchool() = Good School Do student1 and studentinterface1 point to the same object instance? true |
Figure-5.13: Result
Solution: The solution to this step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyPersonInheritanceInterfaces. You can just open it and run it.
Summary
In this exercise, you built a Java program which uses a Java interface which is a child interface of another interface.
Exercise 6: Rewriting an Interface
(6.1) Try to add another method the PersonInterface interface
package mypersoninterfaceproject;public interface PersonInterface {
// Compute person’s total wealth // Get person’s name // Add another method to the interface } |
Code-6.11: Modified PersonInterface.java
2. Observe the compile error in the Person.java. (Figure-6.12 below)
<Learning point> It is not unusual to have one developer (or one Java API specification group) defines a set of Java interfaces and other developers (or groups) implement them. Now if the interface is changed (adding another method to it), the existing implementation classes will be broken. That is what you observed in this step. The solution to this problem is to define another Java interface that contains only the newly added method.
Figure-6.12: The Person class is now broken
3. Remove the change you made in PersonInterface.java in the previous step as shown in Code-6.13 below. This is the original code before thd change.
package mypersoninterfaceproject;public interface PersonInterface {
// Compute person’s total wealth // Get person’s name } |
Code-6.13: PersonInterface.java
4. Write PersonInterfaceAnother.java. The PersonInterfaceAnother interface is a newly created interface that contains newly added method.
package mypersoninterfaceproject;public interface PersonInterfaceAnother {
// Add another method to the interface } |
Code-6.14: PersonInterfaceAnother.java
5. Write PersonAnother.java. The PersonAnother class implements both Person and PersonInterfaceAnother interfaces.
package mypersoninterfaceproject;public class PersonAnother implements PersonInterface, PersonInterfaceAnother{ int cashSaving; // Constructor with arguments // Compute person’s total wealth // Get person’s name // Implement a new method } |
Code-6.15: PersonAnother.java
6. Write PersonAnother2.java. The PersonAnother2 class extends Person class and implements PersonInterfaceAnother interface.
package mypersoninterfaceproject;public class PersonAnother2 extends Person implements PersonInterfaceAnother{
PersonAnother2(){ } // Implement a new method |
Code-6.16: PersonAnother2.java
Solution: The solution to this step is provided as a ready-to-open-and-run NetBeans project as part of hands-on lab zip file. You can find it as <LAB_UNZIPPED_DIRECTORY>/javainterface/samples/MyRewritingInterface. You can just open it and run it.
7. For your exercise, please do the following tasks:
- Create another interface called PersonInterface3 with the following method
- String toChangeNameToUpperCase() // Change name to upper case
- Create another implementation class called PersonAnother3 that implements PersonInterface, PersonInterface2, PersonInterface interfaces
- Modify Main.java to create a object instance of PersonAnother3 and display the name in upper case.
Summary
In this exercise, you have learned how to add new methods to the Java interface without breaking existing code that depends on the existing Java interface.
Homework exercise (for people who are taking Sang Shin’s “Java Programming online course”)
- Write an interface called MyOwnInterface, which has the following method
- AddressInterface getAddress();
- The AddressInterface is a Java interface that has the following methods.
- int getStreetNumber();
- void setStreetNumber(int streetNumber);
- String getStreetName();
- void setStreetName(String streetName);
- String getCountry();
- void setCountry(String country);
- Write AddressImpl class that implements AddressInterface
- Make the Person class to implement MyOwnInterface.
- Initialize a Person object with proper data and display it.
- Zip file of the the MyGetPersonMultipleInterfaces2 NetBeans project. (Someone else should be able to open and run it as a NetBeans project.) You can use your favorite zip utility or you can use “jar” utility that comes with JDK as following.
- cd <parent directory that contains MyGetPersonMultipleInterfaces2 directory> (assuming you named your project as MyGetPersonMultipleInterfaces2)
- jar cvf MyGetPersonMultipleInterfaces2.zip MyGetPersonMultipleInterfaces2 (MyGetPersonMultipleInterfaces2 should contain nbproject directory)
- Captured output screen – name it as JavaIntro-javainterface.gif orJavaIntro-javainterface.jpg (or JavaIntro-javainterface.<whatver graphics format>)
- Any screen capture that shows that your program is working is good enough. No cosmetic polishment is required.
- If you decide to use different IDE other than NetBeans, the zip file should contain all the files that are needed for rebuilding the project – war file with necessary source files is OK.