Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

Inheritance

• The term inheritance refers to the fact that one class can
inherit part or all of its structure and behavior from another
class.
– Structure : fields or attributes.
– Behavior : methods.

• The class that does the inheriting is said to be a subclass


of the class from which it inherits (superclass).
• The subclass can add to the structure and behavior that it
inherits.
• It can also modify or replace inherited behavior (not
inherited structure) by defining methods have the same
signatures as the methods in the superclass (overriding) 1
Inheritance (is-a relationship)
•Class B inherit from or extend Class A

•We say that class A is the parent


(superClass or baseClass) of B.

•B is the child (subClass or derivedClass)


of A.

•Class B has:
•Its fields + fields of class A
•Its methods + methods of class A

•The subclass object is a specialized


superclass type object.
Ex: cat is a pet 2
Inheritance

•In Java, to create a class named B as


a subclass of a class named A , you
would write:

class B extends A {

/* additions to, and modifications of,


stuff inherited from class A */

3
Inheritance and class hierarchy

• Several classes can be declared as sub classes of the


same super class

– They share some structures and behaviors ( the ones


they inherit from their common superclass).
– The superclass expresses these shared structures
and behaviors.

4
Inheritance and class hierarchy
• In the diagram, classes B, C, and D
are sub classes.

• Inheritance can also extend over


several generations of classes.

• class E is a subclass of class D


which is itself a subclass of class A.

• In this case, class E is considered to


be a subclass of class A.

• Classes forms a small class


hierarchy.

• Subclass can extend only one super 5

class.
Object class
• Object class is the super-class of all the classes.

• This means that Object class will be on the top of the


class hierarchy. In other words, the class hierarchy in
Java is a tree, and its root node is the Object class.

• If we do not use keyword extends in a class


declaration, the super-class of that declared class is the
class Object.

class A { ... }
is equivalent to:
class A extends Object { ... }
Design with Inheritance in Mind
• When designing a collection of new but related
classes, pay attention to what are the common
behaviors and characteristics. This process is known
as factorization.
– Try to create a coherent base class that provides this
commonality.
– From the base class, subclasses can be defined to provide
the special behaviors and characteristics.
– Your current work effort should be reduced as common
behaviors are implemented just once.
– Future work efforts should also be minimized as new
features can be added by extending the existing classes.

7
Inheritance - Example

• Consider a program used by a Department of Motor


Vehicles to keep track of registrations.

• The program could use a class named Vehicle to represent


all types of vehicles.

• Since cars, trucks, and motorcycles are types of vehicles,


they would be represented by subclasses of the Vehicle
class.

8
Inheritance - Example

• The Vehicle class would include:


– instance variables such as registrationNumber and owner.
– instance methods such as transferOwnership().
These variables and methods are common to all vehicles.

• The three subclasses of Vehicle— Car, Truck, and Motorcycle —could


then hold variables and methods specific to particular types of vehicles.
– The Car class might add an instance variable numberOfDoors.
– the Truck class might have numberOfAxels.
– and the Motorcycle class could have a boolean variable hasSidecar.

• The declarations of these classes in a Java program would look, in


outline, like next slide:

(Note : they would probably be public classes, defined in separate files)

9
Inheritance - Example

class Vehicle {
protected int registrationNumber;
protected String owner;
public void transferOwnership(String newOwner) {
owner = newOwner;
}
…..
}

class Car extends Vehicle {


private int numberOfDoors;
...
}
class Truck extends Vehicle {
private int numberOfAxels;
...
}
class Motorcycle extends Vehicle {
private boolean hasSidecar;
...
10
}
Members accessibility modifiers

• Up to this point our member variables and methods have


either public or private access rights.
– A public member has no restrictions on its access.
– A private member can only be used by the class that
defines that member.

• With respect to public and private access rights, a


subclass is treated no differently than any other Java
class.
– A subclass can access the superclass’s public
members and cann’t access the superclass’s private
members.
11
Members accessibility modifiers

• Java supports two additional access modifiers:


protected and the default access (package).

• protected modifier:
A subclass can access the superclass s
protected members.

We will not talk about packages in this course


12
Example - Extending The Point Class

• The awt class Point provides a representation of a 2-


dimensional point.

• Using inheritance we will extend this 2-dimensional


point representation to create a 3-dimensional point
class representation, ThreeDPoint.

• The new class ThreeDPoint extends class Point by


adding a new property that the Point class does not
have, namely, a z-coordinate value.

13
Extending The Point Class (cont.)

• This new property can be maintained by using a


private data field z.
• To support encapsulation and information hiding,
ThreeDPoint provides an accessor method getZ()
and a mutator method setZ() for the new z-coordinate
property.

y-axis z-axis

Point (x,y,z) in
3-dimensional
space

14
x-axis
Extending The Point Class (cont.)

• Since we are extending the class ThreeDPoint from


Point. ThreeDPoint inherits the Point x-coordinate
and y-coordinate attributes and Point accessor and
mutator methods getX(), getY(), setX(), and setY().
‒ We ll use these accessors and mutators in our
implementation of ThreeDPoint. The use of these methods
is not necessary because the Point class makes its
attributes public. Our implementation uses these methods
because the use of mutators and accessors is a good
practice ‒ superclass attributes are almost always private
(the Point class is a rare exception to this rule). In the typical
case, a subclass cannot directly access the attributes, and
instead must use the available superclass accessors and
mutators to manipulate the superclass attributes.

15
Extending The Point Class (cont.)

• The ThreeDPoint class also inherits the Point class


facilitators.
E.X., translate(), toString().
However, these Point facilitators are not suitable in a
3-dimensional context ‒ they aren t aware of the z-
coordinate values. Therefore, the ThreeDPoint class
must provide its own versions of these methods .

• We ll look at each of these methods separately.

16
It s All Inherited in Java

• Remember that all classes are an extension of the class


Object. The relationship between ThreeDPoint, Point, and
Object are illustrated in the following diagram.

ThreeDPoint Point Object

Class representing locations Class representing locations Superclass of all Java


with x-, y-, and z- coordinates. with x- and y- coordinates. objects.
ThreeDPoint is a subclass of Point is a subclass of Object.
Point.

Class Object provides basic versions of several methods including: toString(), equals(), and
clone(). It also has methods finalize(), getClass(), hashCode(), notify(), notifyAll(), and wait().
These are all inherited by the subclasses of Object.
17
The ThreeDPoint Class
import java.awt.*;

public class ThreeDPoint extends Point{


//instance variable
private double z;

//ThreeDPoint(): default constructor


public ThreeDPoint(){
super();
}

//ThreeDPoint(): specific constructor


public ThreeDPoint(double a, double b, double
c){
super(a,b);
setZ(c);
}

18
//getZ(): z-coordinate accessor
public int getZ(){
return z; }
//setZ(): z-coordinate mutator
public void setZ(double z){
this.z = z; }

//translate(): shifting facilitator


public void translate(double deltax, double
deltay, double deltaz){
translate(deltax, deltay);
setZ(z+deltaz); }

//toString(): conversion facilitator


public String toString(){
double a = getX();
double b = getY();
double c = getZ();
return getClass() + [ + a + , + b + , +
, + c + ] ;}
}//end class ThreeDPoint 19
Keyword extends
• Keyword extends is Java s mechanism for deriving
a new class from an existing class. Programmers
often read this statement as ThreeDPoint is a kind
of Point.

public class ThreeDPoint extends Point {

Keyword extends indicates that


class ThreeDPoint is a subclass of
its superclass Point

• Let s see the differences between defining a


subclass and a superclass
20
Class Constants and Instance Variables in a
Subclass

• The ThreeDPoint class first defines a private instance


variable z.
• Adding a member to a subclass does not require special
syntax. Therefore, the z declaration has the expected
form:

private double z;

21
Constructors in a Subclass

• The definitions of the ThreeDPoint class constructors


differ from the definitions of previous constructors in
their use of the keyword super.

//ThreeDPoint(): default constructor


public ThreeDPoint(){
super();
Invocation of default
}
superclass constructor

//ThreeDPoint(): specific constructor


public ThreeDPoint(double a,double b,double c)
{
Invocation of specific
super(a,b);
superclass constructor
setZ(c);
} 22
Constructors in a Subclass

• Since a subclass is a specialization of the superclass, The


superclass object must exist before it can be turned into a
specialized subclass object.

• A constructor for the superclass must be invoked to create


a superclass object then the constructor for the subclass
can do its specialization to be an object of that subclass.

• The superclass constructor can be invoked explicitly or


implicitly.

• The keyword super is used to invoke explicitly a


superclass constructor for the subclass object under
construction. 23
Constructors in a Subclass (cont.)

public ThreeDPoint() { super(); }

• Super(); statement in ThreeDPoint default


constructor definition is an explicit invocation of the
superclass s default constructor on the ThreeDPoint
object under construction.

• The Point default constructor takes care of the


initialization of the x- and y- coordinate values.

24
Constructors in a Subclass (cont.)
• The specific ThreeDPoint constructor initializes the
object under construction to the given x-, y-, and z-
coordinate values.

public ThreeDPoint(int a, int b, int c)

• This constructor also explicitly invokes the specific


superclass constructor. to properly set the x- and y-
coordinate values

super(a,b);

• To complete the initialization, the z- coordinate is set


to the desired values using mutator setZ();
25
setZ(c);
Constructors in a Subclass (cont.)

• If a subclass constructor does not invokes explicitly a


superclass constructor, then Java automatically
invokes the superclass s default constructor to
initialize the superclass attributes.

• This means that we could have written our


ThreeDPoint default constructor definition without
explicitly invoking super().

public ThreeDPoint() {
//implicit super() invocation
}
26
Method toString() of Class ThreeDPoint

• Method toString() makes use of its Object inherited


method getClass() in displaying its debugging (String)
representation.

public String toString()


{
int a = getX();
int b = getY();
int c = getZ();

return getClass() + [ + a + , + b + , + ,
+ c + ] ;
}

27
Method getClass()

• Method getClass() returns a String description of the


object s type.
• Ex: consider the following code segment:

ThreeDPoint c = new ThreeDPoint();


System.out.println( c.getClass());

• Displays:

class ThreeDPoint;
28
Method toString() of Class ThreeDPoint

• The ThreeDPoint method toString() should not have different


signature from the Point version.
‒ By having the same signature as its superclass
counterpart, the subclass method overrides the superclass
definition for ThreeDPoint objects. The overriding enables
the subclass-specific nature of the ThreeDPoint objects to
be considered.

ThreeDPoint c = new ThreeDPoint(1, 3, 5);

String s = c.toString(); //invocation of subclass toString() method

29
Method translate() of Class ThreeDPoint

• ThreeDPoint method translate() uses the superclass method


translate() to assist in the shifting of position. However, the
keyword super is not required to invoke the superclass
translate() method because the superclass version uses two
parameters and the subclass version uses three parameters.
• Java can determine from context that it is the superclass
method translate() that is being invoked.

public void translate(double deltax,double deltay,double deltaz){


translate(deltax, deltay);

setZ(z+deltaz); Because there are two parameters


} present, it is the superclass method
translate() being invoked. 30
Method translate() of Class ThreeDPoint

• The ThreeDPoint method translate() has three parameters


representing the increment in the x, y, and z coordinates.
• Since the method signatures of the ThreeDPoint and Point
versions of translate() are different, the method name
translate() is overloaded in the ThreeDPoint class.
‒ This means that with a ThreeDPoint object both methods
are available. Java determines which method is in use
by the number of parameters in a given invocation.

ThreeDPoint a = new ThreeDPoint(5, 20, 47);


a.Translate (1,1); //invocation of superclass translate
a.Translate (2,2,2); //invocation of subclass translate
31
Using the Class ThreeDPoint
• The following code segment illustrates some of the uses of the
class ThreeDPoint.

ThreeDPoint c = new ThreeDPoint();


c.Translate (2,2,2);
ThreeDPoint d = new ThreeDPoint(1,2,3);
System.out.println (c);
System.out.println (d);

• This code segment produces the output:

Class ThreeDPoint[2,2,2]
Class ThreeDPoint[1,2,3]
32
• Why bother with inheritance at all? Why not just
modify the existing class to include the new features?
For example, why not give the Point class a z-
coordinate value?

– Simply adding features can make a class too complex to


understand, build, maintain and test.
– Furthermore, if the source code to an existing class is not
available, then adding new features to that class is not an
option. Most libraries are distributed as compressed
archives or as .class files with .java versions unavailable
– developers often keep the .java versions to themselves
to protect their intellectual investment.

33
Polymorphism

• It s one of the important features of object-oriented programming.


• polymorphism (from the Greek meaning "having multiple forms") is the
characteristic of being able to assign a different meaning or usage to
something in different contexts - specifically, to allow an entity such as a
variable, a method or an object to have more than one form.
There are several different kinds of polymorphism.
1. Method or operator Overloading (primitive polymorphism) – decision is
made at compile time (static binding).
2. Parametric generic programming (Polymorphism can mean, a data type of
any )
3. Pure polymorphism (late binding or dynamic binding or run-time binding)
as decision is made at run-time.
a. Subtype polymorphism and
b. Method invocation polymorphism (overriding polymorphism)
Subtype Polymorphism

Subtype polymorphism is the ability of a single variable to refer to


objects of its type (class) or its subtypes .

class Student { ... }


class Undergraduate extends Student { ... }
class Graduate extends Student { ... }

Student student1;
student1 = new Undergraduate(); // polymorphic assignment
student1 = new Graduate(); // polymorphic assignment

Rule of Polymorphic Assignment:


The type (class) of the expression on the right-side of an
assignment must be the same as type or a subtype of the class of
the variable on the left-hand side of the assignment. 35
Static & Dynamic binding
Consider the following code segment:
class Student { public void m () {..} ……}

class Undergraduate extends Student { public void m () {..}….}

class Graduate extends Student {


public void m () {…}
public void m (int i) {..}
}
Student s;
s = new Student();
s.m(); //Student s m() is executed

s = new Undergraduate();
s.m(); //undergraduate s m() is executed

s= new Graduate();
s.m(); //graduate s m() is executed
36
s.m(5); Compilation error ??
Polymorphic Method Invocation
Dynamic binding

• Which implementation of an overridden method will be invoked


depends on the class of the object referenced by the variable at
run time, not on the declared type of the variable.
• This is known as polymorphic method invocation.
• In polymorphic method invocation, the implementation of a
method is dynamically bound to an invocation at runtime.
• Dynamic binding for a polymorphic method invocation S.m()
proceeds as follows:
1. Compiler checks for m() in Student class (declared type of s)
2. At run-time if m() is implemented in the class of the object
that s refers to, it is invoked else the first level superclass is
checked, if m() is found it is invoked else higher level
superclass is checked and so on.
Polymorphic Method Invocation -- Example
class C {
public void m() { ... } C
}
class C1 extends C {
public void m() { ... }
} C1 C3
class C2 extends C1 { ... }
class C3 extends C { ... }
C2
C x;
x = new x.m(); è m() in C is invoked.
C();
x = new x.m(); è m() in C1 is invoked.
C1();
x = new x.m(); è m() in C1 is invoked.
C2();
x = new x.m(); è m() in C is invoked.
C3();
// x.m(); is a single code expression but
invokes different methods at each
invocation (polymorphic method invocation)
Finality

• Just as Java permits a constant data field to be defined


through the use of the keyword final, it also permits final
methods and classes.
• A final class is a class that cannot be extended.
• A final method is a method that cannot be
overridden.
• The developer of a class might make it final for
economic or security reasons. If clients have access
only to the .class version of a final class, then they must
look to the developer for additional features. As another
example, a class or method may be crucial to a system.
By declaring its finality, it is harder to tamper with the
system by introducing classes that override the existing
code.
39
Finality (cont.)

• Consider class U which is a final class. Therefore, class


U cannot be extended.

final public class U {

//U(): default constructor


public U(){
//no body necessary
}

//f(): facilitator
public void f(){
System.out.println ( U is final can't be extended );
}
}
40
Finality (cont.)
• Consider class V which contains a method f() which is
declared as final. Therefore, method f() cannot be
overridden if V is extended.

public class V {
//V(): default constructor
public V(){
//no body necessary
}

//f(): facilitator

final public void f(){


System.out.println ( Method f() is final can t be overridden );
}
}
41

You might also like