CompSci 230 S2 2015 Software Design and Construction Understanding Inheritance Agenda & Reading  Topics:         Inheritance Constructors Super & this Method Overriding The Object class Method Overloading Polymorphism Reading   Java 2 – The.

Download Report

Transcript CompSci 230 S2 2015 Software Design and Construction Understanding Inheritance Agenda & Reading  Topics:         Inheritance Constructors Super & this Method Overriding The Object class Method Overloading Polymorphism Reading   Java 2 – The.

CompSci 230 S2 2015
Software Design and Construction
Understanding Inheritance
Agenda & Reading

Topics:








Inheritance
Constructors
Super & this
Method Overriding
The Object class
Method Overloading
Polymorphism
Reading


Java 2 – The Complete Reference, Chapter 8, page 193-211
The Java Tutorial :



2
Polymorphism
Overriding and Hiding Methods:
Using the Keyword super
05
Inheritance




Inheritance is a way to form new classes (instances of which are called objects)
using classes that have already been defined.
The former, known as derived classes, take over (or inherit) attributes and
behaviour of the latter, which are referred to as base classes.
It is intended to help reuse of existing code with little or no modification.
Rules:

Derived class (subclass)



Inherits all the public variables and methods of a base class
Adds additional variables and methods
Can change the meaning of inherited methods (override methods)
Example: Person & Employee
getSalary() –
Additional method
getIRD(),
getNames():
inherit from Person
3
05
Example: ColoredSphere.java
Example:

SimpleSphere
&
ColoredSphere
The Sphere class is a base class

Variable:


radius
Methods:

setRadius(…), diameter(), area(), circumference(), toString() …
public class Sphere {
protected double theRadius;
public Sphere() {
setRadius(1.0);
}
public Sphere(double r) {...}
public void setRadius(double r) {...}
public double radius() { ... }
public String toString() {...}
...
}
4
05
Example:

&
ColoredSphere
The ColoredSphere is a derived class that





5
SimpleSphere
Inherits a field (radius) from the base class,
Inherits a few methods (setRadius, diameter … etc) from the base
class,
Adds a new field: color
Adds two new methods: setColour(…), getColour()
Overrides an existing method (toString) from the base class.
public class ColoredSphere extends SimpleSphere {
private Color color;
public ColoredSphere(Color c) {
super();
color = c;
}
public void setColor(Color c) { ... }
public Color getColor() {...}
public String toString() {
return super.toString() + ...}
...
}
05
Constructor


A constructor in a class is a special method (function) that can be used to create
objects of the class and never has a return type.
Rules:

Each Subclass constructor must always call the superclass constructor (explicitly or
implicitly)


Implicitly: calls its superclass default no-argument constructor
Explicitly: using super()

If you call the superclass constructor explicitly, then the compiler will not call it implicitly.
class A1 {
int x;
public A1() {
class B1 extends A1 { Calls constructor
x=1;
implicitly
int y;
System.out.println("called A1()");
public B1() {
}
System.out.println("called B1()");
public A1(int x) {
}
this.x = x;
public B1(int x, int y) { Calls constructor
System.out.println("called A1(x)");
explicitly
super(x);
}
this.y = y;
}
called A1()
System.out.println("called B1(x,y)");
called B1()
}
B1 b1 = new B1();
}
B1 b2 = new B1(10, 100);
called A1(x)
Example: B1.java
called B1(x,y)
6
05
Constructor

Rules:

A subclass cannot inherit constructors from the base class. Each subclass
should define its constructor

If no constructor is defined, the compiler adds a single zero-parameter default
constructor for the class and applies the default initialization for any data fields.
class A1 {
int x;
public A1() {
x=1;
System.out.println("called A1()");
}
public A1(int x) {
this.x = x;
System.out.println("called A1(x)");
}
}
class B extends A1 {
int y = 10;
public B(int x) {
super(x);
}
}
7
class B2 extends A1 {
int y = 10;
Add a single zero-parameter
default constructor
}
Calls base class’s
constructor implicitly
B2 b = new B2();
System.out.println("b.x=" + b.x);
System.out.println("b.y=" + b.y);
B2 b = new B2(10);
B b = new B();
Compile time error
- No zero-parameter
constructor
called A1()
b.x=1
b.y=10
Compile time error
- No constructor with an
integer argument
Example: B2.java
05
Constructor

Rules:


You can only call a superclass constructor from a subclass constructor,
not from any other subclass method
Never place any subclass constructor code ahead of its superclass
constructor call (reason: a subclass constructor’s initialisation may depend
on the values declared in a superclass)
class A1 {
int x;
public A1() {
x=1;
System.out.println("called A1()");
}
public A1(int x) {
this.x = x;
System.out.println("called A1(x)");
}
}
B3 b = new B3(100);
System.out.println("b.x=" + b.x);
System.out.println("b.y=" + b.y);
8
class B3 extends A1 {
int y = x + 10;
public B3(int x) {
super(x);
}
}
called A1(x)
b.x=100
b.y=110
Example: B3.java
05
public, private & protected

Classes, and their fields and methods have access levels to
specify how they can be used by other objects during
execution



9
A private field or method is accessible only to the class in which it
is defined.
A protected field or method is accessible to the class itself, its
subclasses,
A public field or method is accessible to any class of any parentage
in any package
05
public, private & protected
Example:

public class Sphere {
protected double theRadius;
public Sphere() {
setRadius(1.0);
}
public Sphere(double r) {...}
public void setRadius(double r) {...}
public double radius() { ... }
public class ColoredSphere extends SimpleSphere {
public String toString() {...}
private Color color;
...
public ColoredSphere(Color c) {
}
super();
color = c;
}
public void setColor(Color c) { ... }
public Color getColor() {...}
public String toString() {
return super.toString() + ...}
...
public void method1() {
System.out.println(super.theRadius);
}
}
10
05
Usage of super & this

super

Constructor : super() or super(…)




Automatically called in derived constructor if not explicitly called
Call to super() must be the first call in constructor
Cannot call super.super()
super.member


Members can be either method or instance variables
Refers to the members of the superclass of the subclass in which it is used



Used from anywhere within a method of the subclass
this



Can be used inside any method to refer to the current object
Constructor: this(), this(…): refer to its constructor
this.member


Members can be either method or instance variables
this.instance_variable:

11
Note: a variable that has the same name as a variable in the superclass hides the superclass's member
variable. The variable in the superclass cannot be referenced by its name and it must be accessed
through “super” (later this week)
To resolve name-space collisions that might occur between instance variables and local variables
05
Method Overriding


If an inherited property or method needs to behave differently in the derived
class it can be overridden; that is, you can define a new implementation of the
method in the derived class.
You can change the meaning (override) of the method declared in the superclass


Completely, or
Add more functionality to the method


The new method can call the original method in the parent class by specifying Super before
the method name.
Rules:


A Subclass cannot override final methods declared in the base class.
The Overridden method must have the same arguments as the inherited method from
the base class.
class Base2 {
public final void finalMethod() {
Example: Derived2.java
System.out.println("called Base:finalMethod");
}
public class Derived2 extends Base2 {
}
public final void finalMethod() {
Final methods cannot be
overridden.
12
System.out.println("called Derived:finalMethod");
...
05
class Base {
public void aMethod() {
System.out.println("called Base:aMethod");
}
}
public class Derived extends Base {
This method defined by the
public void aMethod() {
subclass is overridden to the
System.out.println("called Derived:aMethod");
method defined in the superclass.
}
public static void main(String[] args) {
Derived d = new Derived();
called Derived:aMethod
d.aMethod();
}
}
class Base {
public void add() {
System.out.println("called Base:add");
}
}
Overriding
public class Derived extends Base {
Use super.methodName() to call the
public void add() {
method defined in the superclass
super.add();
System.out.println("called Derived:add");
}
public static void main(String[] args) {
Derived d = new Derived();
d.add();
Example: Derived.java
}
}
13
05
Object
The Object class




Every java class has Object as its superclass and thus inherits the
Object methods.
Object is a non-abstract class
Many Object methods, however, have implementations that aren’t
particularly useful in general
In most cases it is a good idea to override these methods with
more useful versions.


14
…
equals: compares two objects for equality and returns true if they are
equal.
toString: returns a String representation of the object
public class Object {
...
public boolean equals(Object obj) {
return (this == obj);
}
public String toString() {
return getClass().getName() ...
}
}
05
The toString() method


It is intended to return a readable textual representation of
the object upon which it is called. This is great for debugging!
Every class has a toString, even if it isn't in your code.

The default toString returns the class's name followed by a
hexadecimal (base-16) number
System.out.println(someObject);

Replace the default behaviour by overriding the toString
method in your class
public String toString() {
return "(" + x + ", " + y + ")";
}
15
05
The equals() method

By default, equals(Object o) does exactly what the == operator
does – compare object references



That is, two object are the same if the point to the same memory.
Since java does not support operator overloading, you cannot change this
operator.
However, the equals method of the Object class gives you a chance to
more meaningful compare objects of a given class.

returns true if they are actually the same object
Sphere sphere1 = new Sphere();
Sphere sphere2 = sphere1;
if (sphere1.equals(sphere2)) {
System.out.println("same");
} else {
System.out.println("different");
}
same
16
Sphere sphere1 = new Sphere(2.0);
Sphere sphere3 = new Sphere(2.0);
if (sphere1.equals(sphere3)) {
System.out.println("same");
} else {
System.out.println("different");
}
different
05
The customize equals method

To override, simply override method with version that does
more meaningful test, i.e. compares values and returns true if
equal, false otherwise

E.g. An equals methods that determines whether two sphere have
the same radius
public boolean equals(Object rhs) {
return (rhs instanceof MySphere) &&
(theRadius == ((MySphere) rhs).radius());
}
MySphere sphere1 = new MySphere();
MySphere sphere2 = sphere1;
if (sphere1.equals(sphere2)) {
System.out.println("same");
} else {
System.out.println("different");
}
17
same
MySphere sphere1 = new MySphere(2.0);
MySphere sphere3 = new MySphere(2.0);
if (sphere1.equals(sphere3)) {
System.out.println("same");
} else {
System.out.println("different");
}
same
05
Method Overloading
Example: Overload.java
Method overloading is the process of using the same method name for multiple
methods
The signature of each overloaded method must be unique





The signature includes the number, type, and order of the parameters
The return type of the method is NOT part of the signature
The compiler must be able to determine which version of the method is being invoked
by analysing the parameters
public void aMethod() {
System.out.println("called aMethod()");
}
Zero-parameter
public void aMethod(int x, String y, boolean z) {
System.out.println("called aMethod(int x, String y, boolean z)");
}
public void aMethod(String y, int x, boolean z) {
System.out.println("called aMethod()");
}
3-parameters (int, String, boolean)
3-parameters (String, int, boolean)
Not Overloaded
18
public int aMethod(int x, String y, boolean z) {
...
error: aMethod(int,String,boolean) is already defined in…
05
Sphere
Types

We can create an instance in the following way:
ColoredSphere
ColoredSphere s1 = new ColoredSphere(Color.blue);
Type of the variable (LHS) = type created of the ColoredSphere created (RHS)

An ColoredSphere object is also an Sphere object and it is
also an Object. Therefore, we can assign …
Sphere s2 = new ColoredSphere(Color.green);
Object obj1 = new ColoredSphere(Color.red);
System.out.println(s1); // call the toString() from ColoredSphere
System.out.println(s2); // call the toString() from ColoredSphere
System.out.println(obj1); // call the toString() from ColoredSphere
Sphere s3 = new Sphere(10);
System.out.println(s3);
//call the toString() from Sphere
19
05
Sphere
Polymorphism


ColoredSphere
This occurs when one method name in a method call can
cause different actions depending on which type of instance is
invoking the method. !
At runtime, the actual method corresponding to the instance
type is executed (i.e., the method defined in the class whose
constructor created the object):!
System.out.println(s1); // call the toString() from ColoredSphere
System.out.println(s2); // call the toString() from ColoredSphere
System.out.println(obj1); // call the toString() from ColoredSphere
Sphere s3 = new Sphere(10);
System.out.println(s3);
//call the toString() from Sphere
20
05
Polymorphism

Definition:


Polymorphism is the ability of objects belonging to different types to
respond to method calls of methods of the same name, each one
according to an appropriate type-specific behaviour. The program does
not have to know the exact type of the object in advance, so this behavior
can be implemented at run time (this is called late binding or dynamic
binding).
Example:

Classes:






21
Kitchen
Person
HouseWife
PizzaChef
KFCChef
TakeAwayChef
05
Example

Our COMPSCI230Kitchen has a Person



A person has surname and first name
Create a person in our COMPSCI230Kitchen
Person


Person
Kitchen
Instance variables: surname and first name
HouseWife
Methods:


getName() get surname and first name
cookDinner() to prepare food for dinner

An ordinary person prepares dinner using microwave!
PizzaChef
getName
cookDinner
KFCChef
TakeAwayChef
public class Person {
String surname;
String firstname;
...
public void cookDinner() {
System.out.println("Microwave Dinner");
}
}
Person p = new Person();
22
System.out.println(p.getName());
p.cookDinner();
05
HouseWife
Now our COMPSCI230Kitchen has a houseWife person
HouseWife
p = new HouseWife();



Inherited method: getName


Additional method: cleanKitchen


To get her name
To clean our kitchen
Overridden method: cookDinner


To cook food for dinner
A housewife makes Roast chicken with Potato.
public class HouseWife extends Person {
public HouseWife(String firstname, String surname) {
super(firstname, surname);
}
public void cookDinner() {
System.out.println("Roast Chicken with Potato");
}
public void cleanKitchen() {
System.out.println("Cleaning now");
}
}
23
Person
HouseWife
getName
cookDinner
cleanKitchen
System.out.println(p.getName());
p.cookDinner();
05
PizzaChef
Now our COMPSCI230Kitchen has a PizzaChef person
p = new PizzaChef();
PizzaChef



Inherited method: getName


To get her name
Overridden method: cookDinner


To cook food for dinner
A pizzachef makes Pizza
Person
PizzaChef
System.out.println(p.getName());
p.cookDinner();
public class PizzaChef extends Person {
public PizzaChef(String firstname, String surname) {
super(firstname, surname);
}
public void cookDinner() {
System.out.println("Pizza");
}
}
24
05
KFCChef
Now our COMPSCI230Kitchen has a KFCChef person
p = new KFCChef();
KFCChef



Inherited method: getName


To get her name
Overridden method: cookDinner


To cook food for dinner
A KFCChef makes KFC fried chicken
Person
kFCChef
System.out.println(p.getName());
p.cookDinner();
public class KFCChef extends Person {
public KFCChef(String firstname, String surname) {
super(firstname, surname);
}
public void cookDinner() {
System.out.println("KFC Chicken");
}
}
25
05
TakeAwayChef
Now our COMPSCI230Kitchen has a TakeAwayChef person
p = TakeAwayChef();
TakeAwayChef



Inherited method: getName


To get her name
Overridden method: cookDinner


To cook food for dinner
A TakeAwaychef makes fried rice
Person
TakeAwayChef
System.out.println(p.getName());
p.cookDinner();
public class TakeAwayChef extends Person {
public TakeAwayChef(String firstname, String surname) {
super(firstname, surname);
}
public void cookDinner() {
System.out.println("Fried Rice");
}
}
26
05
Example:Kitchen.java
An array of Person



The array holds five objects of type Person.
Because of their inheritance relationship with the Person class, the
HouseWife, PizzaChef, KFCChef and TakeAwayChef classes can be
assigned to the array.
Within the for-loop, the cookDinner method is invoked on each
element of the array.


At first, when a method call is executed, the object is checked first and if
the method does not exist, then check the superclass (work from the child
to the parent class) – Type checking is done at compile time
Next, the method is executed based on the object, not on the type of
variable. The derived classes override the cookDinner method of the
Person class. This makes the overridden cookDinner() methods of the
derived classes execute when the cookDinner() method is called using the
base class reference from the array
Person[] pList = new Person[5];
pList[0] = new Person("Dick", "Smith");
pList[1] = new HouseWife("Theresa", "Thompson");
pList[2] = new PizzaChef("Michael", "Hill");
pList[3] = new KFCChef("Peter", "Wong");
pList[4] = new TakeAwayChef("Kevin", "Chan");
for (int i=0; i<pList.length; i++)
pList[i].cookDinner();
27
The result depends on
the object stored, not on
the type of the variable.
05
Rules

Polymorphism is the ability of objects belonging to different types
to respond to method calls of methods of the same name, each
one according to an appropriate type-specific behaviour.

At Compile time,


the type of each variable is checked to ensure that only methods belonging to
that type are called
At Run time,

the code executed depends on the nature of the object, not the type of the
variable.
HouseWife w;
w = new HouseWife("Theresa", "Thompson");
w.cookDinner();
w.cleanKitchen();
Person p1;
p1 = new HouseWife("Theresa", "Thompson");
p1.cookDinner();
//p1.cleanKitchen(); //Compile error
28
No cleanKitchen method
declared in Person class.
05
Review



Except for the Object class, a class has exactly one direct
superclass.
A class inherits fields and methods from all its superclasses,
whether direct or indirect.
Overloading VS Overriding

29
Same method name & …
Within a class
Parent & Child class
Same method signature
Compile-time error
Overriding
different method signature
Overloading
Overloading
05