Lesson Set 9 Inheritance and Polymorphism: Purpose

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Lesson Set Inheritance and Polymorphism

9
Purpose 1. Write programs that are easily extensible and modifiable by
applying polymorphism in program design.
2. Define reusable classes based on inheritance and abstract
classes and abstract methods.
3. Differentiate the abstract classes

Procedure 1. Students should read the Pre-lab Reading Assignment


before coming to lab.
2. Students should complete the Pre-lab Writing Assignment
before coming to lab.
3. In the lab, students should complete Labs 1.1 through 1.4
in sequence.
4. Your instructor will give further instructions as to grading
and completion of the lab.
5. Students should complete the set of lab tasks before the
next lab and get them checked by their lab instructor.

Contents Pre-requisites Completion


Time

Pre-lab Reading Assignment - 10 min

Lab 1 understanding of 30 min


Exploring Inheritance classes and
objects

Lab 2 understanding of 30 min


Overriding the equals classes and
Method objects

Introduction: Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part of OOPs
(Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of the parent class. Moreover, you can add new methods
and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.
Why use inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Terms used in Inheritance
o Class: A class is a group of objects which have common properties. It is
a template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class.
It is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.
The syntax of Java Inheritance
1. class Subclass-name extends Superclass-name  
2. {  
3.    //methods and fields  
4. }  
The extends keyword indicates that you are making a new class that derives from
an existing class. The meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or
superclass, and the new class is called child or subclass.

Lab Task 1

Create a class Dog.java and copy-paste the below code:


//
**********************************************
******************
// Dog.java
//
// A class that holds a dog's name and can
make it speak.
//
//
**********************************************
******************
public class Dog
{
protected String name;
//
----------------------------------------------
--------------
// Constructor -- store name
//
----------------------------------------------
--------------
public Dog(String name)
{
this.name = name;
}
//
----------------------------------------------
--------------
// Returns the dog's name
//
----------------------------------------------
--------------
public String getName()
{
return name;
}
//
----------------------------------------------
--------------
// Returns a string with the dog's comments
//
----------------------------------------------
--------------
public String speak()
{
return "Woof";
}
}
Create a class Labrador.java and copy-paste the below code:

//
**********************************************
******************
// Labrador.java
//
// A class derived from Dog that holds
information about
// a labrador retriever. Overrides Dog speak
method and includes
// information about avg weight for this
breed.
//
//
**********************************************
******************
public class Labrador extends Dog
{
private String color; //black, yellow, or
chocolate?
private int breedWeight = 75;
public Labrador(String name, String color)
{
this.color = color;
}
//
----------------------------------------------
--------------
// Big bark -- overrides speak method in Dog
//
----------------------------------------------
--------------
public String speak()
{
return "WOOF";
}
//
----------------------------------------------
--------------
// Returns weight
//
----------------------------------------------
--------------
public static int avgBreedWeight()
{
return breedWeight;
}
}
Create a class Yorkshire.java and copy-paste the below code:

//
**********************************************
******************
// Yorkshire.java
//
// A class derived from Dog that holds
information about
// a Yorkshire terrier. Overrides Dog speak
method.
//
//
**********************************************
******************
public class Yorkshire extends Dog
{
public Yorkshire(String name)
{
super(name);
}
//
----------------------------------------------
--------------
// Small bark -- overrides speak method in
Dog
//
----------------------------------------------
--------------
public String speak()
{
return "woof";
}
}

Create a class DogTest..java and copy-paste the below code:

//
**********************************************
******************
// DogTest.java
//
// A simple test class that creates a Dog and
makes it speak.
//
//
**********************************************
******************
public class DogTest
{
public static void main(String[] args)
{
Dog dog = new Dog("Spike");
System.out.println(dog.getName() + " says " +
dog.speak());
}
}

File Dog.java contains a declaration for a Dog class. Save this file to your directory and study it—notice
what instance variables and methods are provided. Files Labrador.java and Yorkshire.java contain
declarations for classes that extend Dog. Save and study these files as well.

File DogTest.java contains a simple driver program that creates a dog and makes it speak. Study
DogTest.java, save it to your directory, and compile and run it to see what it does. Now modify these files
as follows:

1. Add statements in DogTest.java after you create and print the dog to create and print a Yorkshire
and a Labrador. Note that the Labrador constructor takes two parameters: the name and color of
the Labrador, both strings. Don't change any files besides DogTest.java. Now recompile
DogTest.java; you should get an error saying something like

./Labrador.java:18: Dog(java.lang.String) in Dog cannot be applied to () { ^ 1 error

If you look at line 18 of Labrador.java it's just a {, and the constructor the compiler can't find
(Dog()) isn't called anywhere in this file.
a. What's going on? (Hint: What call must be made in the constructor of a subclass?) =>
b. Fix the problem (which really is in Labrador) so that DogTest.java creates and makes
the Dog, Labrador, and Yorkshire all speak.

2. Add code to DogTest.java to print the average breed weight for both your Labrador and your
Yorkshire. Use the avgBreedWeight() method for both. What error do you get? Why?

Fix the problem by adding the needed code to the Yorkshire class.

Save these changes and recompile DogTest.java. You should get an error in Dog.java (unless you made
more changes than described above). Figure out what's wrong and fix this error, then recompile
DogTest.java. You should get another error, this time in DogTest.java. Read the error message carefully; it
tells you exactly what the problem is. Fix this by changing DogTest (which will mean taking some things
out).
Your code and output here.

You might also like