Transcript

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Objectives of today’s lab:

Through this lab, students will explore a hierarchical model for object-oriented design and examine

the capabilities of the Java language provides for inheritance and polymorphism.

Inheritance is a Java (OO) language feature by which a

new type can be declared that extends the capabilities

of an existing type.

Polymorphism is a language feature that allows the

same function call to be associated with different

definitions during the same program's execution, by

delaying the binding of the call to run-time. [More on

this in the next lab]

Create a Java project named week9

Create a package named basicoop2 in the

project week9

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Exercise 1: Understanding the basic concept of

Inheritance

When you inherit from an existing class, you can reuse methods and fields of parent

class, and further you can add new methods and fields also to your derived class.

Task 1.1. Write the following program, save, compile, and run it.

/* file name should be TestInheritance.java in the basicoop2 package*/

class Animal{

public void eat(){

System.out.println("Eating!");

}

}

class Cat extends Animal{

public void meow (){

System.out.println("Meowing!");

}

}

public class TestInheritance{

public static void main(String args[]){

Cat cat = new Cat();

cat.eat();

cat.meow();

}

}

If you can successfully run your program, you should see the following output:

Eating!

Meowing!

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Task 1.2. Modify the above program as highlighted below, save, compile,

and run it.

class Animal{

public Animal(){

System.out.println("Animal Constructor called!");

}

public void eat(){

System.out.println("Eating!");

}

}

class Cat extends Animal{

public Cat(){

System.out.println("Cat Constructor called!");

}

public void meow (){

System.out.println("Meowing!");

}

}

public class TestInheritance{

public static void main(String args[]){

Cat cat = new Cat();

cat.eat();

cat.meow();

}

}

If you can successfully run your program, you should see the following output:

Animal Constructor called!

Cat Constructor called!

Eating!

Meowing!

Task 1.3: Can you explain what’s happening here and why? (Just write as a comment in the

code).

(Note that, you have not created any object of the Animal class but its constructor has been called)

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Task 1.4. (Use of super) Modify the above program as highlighted below,

save, compile, and run it.

class Animal{

int animalAge;

public Animal(){

System.out.println("Animal Constructor called!");

}

public Animal(int animalAge){

this.animalAge = animalAge;

System.out.println("Animal Constructor called using super!");

}

public int getAnimalAge() {

return animalAge;

}

public void eat(){

System.out.println("Eating!");

}

}

class Cat extends Animal{

public Cat(int catAge){

super(catAge);

}

public Cat(){

System.out.println("Cat Constructor called!");

}

public void meow (){

System.out.println("Meowing!");

}

public int getCatAge() {

return this.animalAge;

}

}

public class TestInheritance{

public static void main(String args[]){

Cat cat = new Cat(2);

cat.eat();

cat.meow();

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

System.out.println("Cat's age: "+cat.getCatAge());

}

}

If you can successfully run your program, you should see the following output:

Animal Constructor called using super!

Eating!

Meowing!

Cat's age: 2

Task 1.5: Now, in your code change the access modifier of int animalAge according to the

following and observe the corresponding results

(a) public int animalAge;

Save, compile, and run the modified program

(b) protected int animalAge;

Save, compile, and run the modified program

(c) private int animalAge;

Save, compile, and run the modified program

Note that, a subclass does not inherit the private members of its base class. However, if the

base class has public or protected methods for accessing its private fields, these can also be

used by the subclass. Therefore, in this case you can use the following getCatAge()

implementation to make it work.

public int getCatAge() {

return this.getAnimalAge();

}

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Task 1.6: (Use of super continued) Modify the above program according to the following:

In the Cat class:

Declare a String data field named color

private String color;

Modify the Cat(int catAge) constructor to

Cat(int catAge, String color){

//implement the code here, you must use super to call the Animal

constructor

}

Write a getColor() method that return color

In the main method, modify the code according to the following:

Cat cat = new Cat(2, "Blue");

cat.eat();

cat.meow();

System.out.println("Cat's age: "+cat.getAnimalAge());

System.out.println("Cat's color: "+cat.getColor());

If you can successfully run your program, you should see the following output:

Animal Constructor called using super!

Eating!

Meowing!

Cat's age: 2

Cat's color: Blue

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Task 1.7: (Use of overriding method) Modify the above program according to the following:

In the Animal class, change the print statement in the eat() method according to the following:

public void eat(){

System.out.println("Animal Eating!");

}

}

In the Cat class, implement the same eat() method according to the following:

public void eat(){

System.out.println("Cat Eating!");

}

}

When you do this, Netbeans editor will suggest you to Add @Override Annotation, you just accept

the suggestion. Now save, compile, and run the modified program. Your main() method remains

the same as below:

public static void main(String args[]){

Cat cat = new Cat(2, "Blue");

cat.eat();

cat.meow();

System.out.println("Cat's age: "+cat.getAnimalAge());

System.out.println("Cat's color: "+cat.getColor());

}

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

If you can successfully run your program, you should see the following output:

Animal Constructor called using super!

Cat Eating!

Meowing!

Cat's age: 2

Cat's color: Blue

Observation: Note that both versions of the eat() method are members of the Cat class.

However, in the output you see Cat Eating! (and not the Animal Eating!).

Can you explain, why? (Just write as a comment in the code).

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Exercise 2: Design and Implementation

You should work in small groups of 2/3 students

Your starting point will be to consider a simple example based on people. Suppose you are

developing a software system for UWE. They have already designed, written, coded and tested a

class called Person. An object in this class holds personal information about somebody using his

name and address. A Person also has methods that can construct a new person from given data,

print the information in a standard format, set the name and address and so on. Now UWE also

wants a Lecturer class, a Student class, and a GraduateStudent class that are all different kinds of

People!

A UML class diagram of the Person class and its corresponding Java code implementation are shown

below. Note that all the member variable are private and methods are public.

Person

-firstName: String

-lastName: String

-address: String

+Person() +Person(firstName: String, lastName: String, address: String) +setFirstName(firstName: String): void +getFirstName(): String +setLastName(lastName: String): void

+getLastName(): String

+setAddress(address: String): void +getAddress(): String

+toString(): String

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

public class Person {

private String firstName;

private String lastName;

private String address;

public Person() {

}

public Person(String firstName, String lastName, String address)

{

this.firstName = firstName;

this.lastName = lastName;

this.address = address;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

@Override

public String toString() {

return "Person's name is " + getFirstName() +" "+

getLastName() +"\n Address is "+ getAddress();

}

public static void main(String args[])

{

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Person p = new Person();

System.out.println(p);

p.setFirstName("Abdur");

p.setLastName("Rakib");

p.setAddress("UWE Frenchay Campus");

System.out.println(p);

Person p1 = new Person("Jun", "Hong", "UWE Frenchay Campus");

System.out.println(p1);

}

}

Task 2.1: Study the Person class diagram and the corresponding Java code. Write, save, compile,

and run the above code.

/* file name should be Person.java in the basicoop2 package*/

If you can successfully run your program, you should see the following output:

Person's name is null null

Address is null

Person's name is Abdur Rakib

Address is UWE Frenchay Campus

Person's name is Jun Hong

Address is UWE Frenchay Campus

Observation: carefully look at the toString() method to understand how it works (if necessary

look at the lecture slides or ask your tutor).

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Task 2.2. Design three classes Lecturer, Student, and GraduateStudent using pen and paper (or

you can use MS Word/PowerPoint editor). The classes Lecturer and Student extend Person, and

GraduateStudent extends Student. Draw the complete UML class diagram considering all the four

classes. Your three newly designed classes contain the following:

Lecturer class:

One integer data field representing lecturer ID

A no-argument constructor that creates a default lecturer

A constructor that creates a lecturer with the specified name, address, and the lecturer ID

(note that you need to access name and address from the base class)

All the appropriate ‘set’ and ‘get’ methods

A method named toString() that returns a string description for the lecturer

Student class:

One integer data field representing student ID

A no-argument constructor that creates a default student

A constructor that creates a student with the specified name, address, and the student ID

(note that you need to access name and address from the base class)

All the appropriate ‘set’ and ‘get’ methods

A method named toString() that returns a string description for the student

GraduateStudent class:

One String data field representing supervisor’s name (usually, a graduate student works

under an assigned supervisor)

A no-argument constructor that creates a default graduate student

A constructor that creates a graduate student with the specified name, address, the student

ID, and the supervisor’s name (note that you need to access name, address, and student ID

from the base class)

All the appropriate ‘set’ and ‘get’ methods

A method named toString() that returns a string description for the graduate student

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Task 2.3: Implement your classes

Extend your program by implementing the three new classes.

(a) Implement your Lecturer class first, make the class Lecturer extend the class Person by

adding “extends Person” to the right of the class declaration. This is an inheritance

relationship, so Lecturer now immediately inherits all the public members and methods of B.

When implementing its constructor that takes THREE parameters, use two parameters to

call the Person constructor by using the super keyword. Your constructor should look like

this

public Lecturer(String firstName, String lastName, String address,

int lecturerID){

//add code

}

In the //add code section, if you place any code before the super, you should note the

resulting compiler error. The problem is that the super class constructor must be called before any

other code. Your tutor may explain why this must be so. If you have done this mistake, then move

the call to the super class constructor to the start of the method and the error will go away. Copy

the remaining lecturerID value to the member variable of the same name, using the "this"

keyword.

Override the toString() method to return all the three variables. When implementing this, you

must use super to call base class ‘get’ methods. For example, your code should look like this

@Override

public String toString() {

return "Lecturer's name is " + super.getFirstName() +" "+ super.getLastName() +"\n Address is

"+ super.getAddress() +"\n Lecturer ID: " +getLecturerID();

}

}

Save, compile, and run your code by creating the following object and printing its information

Lecturer lecturer = new Lecturer ("Abdur", "Rakib","UWE Frenchay

Campus",1234);

System.out.println(lecturer);

If you can successfully run your program, you should see the following output:

Lecturer's name is Abdur Rakib

Address is UWE Frenchay Campus

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Lecturer ID: 1234

(b) Similarly, implement other two classes. Save, compile, and run your code by creating the

following objects and printing their information

Lecturer lecturer = new Lecturer ("Abdur", "Rakib","UWE Frenchay

Campus",1234);

System.out.println(lecturer);

Student student = new Student ("Peter", "Miller","UWE Frenchay

Campus",5678);

System.out.println(student);

GraduateStudent gradstudent = new GraduateStudent ("Dan",

"Fielding","UWE Frenchay Campus",1357,"Andy King");

System.out.println(gradstudent);

If you can successfully run your program, you should see the following output:

Lecturer's name is Abdur Rakib

Address is UWE Frenchay Campus

Lecturer ID: 1234

Students's name is Peter Miller

Address is UWE Frenchay Campus

Student ID: 5678

Students's name is Dan Fielding

Address is UWE Frenchay Campus

Student ID: 1357

Supervisor’s name: Andy King

Week 9(18) OOSD1 Java lab exercises: Java Inheritance and Polymorphism

Congratulations! Today, you have learned an important feature of the object-oriented

programming languages. Now please help your fellow classmates who have been struggling to

complete these exercises OR if you like:

(i) Change the access specifier of the member variables of the Person class and play with

them.

(ii) Extend your program by adding new classes. For example, UnderGradaute,

PermanentLecturer, and PartTimeLecturer.


Top Related