Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
67 views

05 JavaInheritance

Inheritance allows one class to inherit attributes and behaviors from another class. The inheriting class contains all the attributes and methods of the parent class plus any new attributes and methods defined in the inheriting class. The inheriting class can override existing parent class methods by providing its own implementation. Inheritance allows for code reuse and localization of changes to the parent class.

Uploaded by

kikiriclovan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

05 JavaInheritance

Inheritance allows one class to inherit attributes and behaviors from another class. The inheriting class contains all the attributes and methods of the parent class plus any new attributes and methods defined in the inheriting class. The inheriting class can override existing parent class methods by providing its own implementation. Inheritance allows for code reuse and localization of changes to the parent class.

Uploaded by

kikiriclovan
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Inheritance

ƒ A class can be a sub-type of another class


ƒ The inheriting class contains all the
methods and fields of the class it inherited
Inheritance from plus any methods and fields it defines
ƒ The inheriting class can override the
definition of existing methods by providing
its own implementation
ƒ The code of the inheriting class consists
only of the changes and additions to the
base class
Version 2 - June 2008

Example Overriding
ƒ Class Employee{ ƒ Class Vector{
string name;
double wage;
int vect[20];
void incrementWage(){…} void add(int x) {…}
} }
ƒ Class Manager extends Employee{ ƒ Class OrderedVector extends Vector{
string managedUnit;
void changeUnit(){…} void add(int x){…}
} }
ƒ Manager m = new Manager();
m.incrementWage(); // OK, inherited
Why inheritance Inheritance in real Life
ƒ Frequently, a class is merely a modification ƒ A new design created by the
of another class. In this way, there is modification of an already existing
minimal repetition of the same code design
ƒ Localization of code Š The new design consists of only the
Š Fixing a bug in the base class automatically fixes changes or additions from the base
it in the subclasses
design
Š Adding functionality in the base class
automatically adds it in the subclasses ƒ CoolPhoneBook inherits PhoneBook
Š Less chances of different (and inconsistent) Š Add mail address and cell number
implementations of the same operation

Example of inheritance tree Inheritance terminology


ƒ Class one above
Living species

Š Parent class
ƒ Class one below
Animal vegetal

Human being Š Child class

Professor
Flower ƒ Class one or more above
SalesMan Š Superclass, Ancestor class, Base class
Student
ƒ Class one or more below
Travel Agent Š Subclass, Descendent class
Inheritance and polymorphism Inheritance and polymorphism
Class Employee{
private string name; Employee e1 = new Employee();
ƒ Employee e1 = new Employee();
public void print(){ Employee e2 = new Manager();
System.out.println(name); e1.print(); // name ƒ Employee e2 = new Manager(); //ok, is_a
} e2.print(); // name and unit ƒ e1.print(); // name
}
ƒ e2.print(); // name and unit
Class Manager extends Employee{
private string managedUnit;

public void print(){ //overrides


System.out.println(name); //un-optimized!
System.out.println(managedUnit);
}
}

Inheritance in few words Inheritance in Java: extends


class
class Car
Car {{
ƒ Subclass String
Car String color;
color;
Š Inherits attributes and methods
boolean
boolean isOn;
isOn;
color String
String licencePlate;
licencePlate;
Š Can modify inherited attributes and
isOn
licencePlate void
void paint(String
paint(String color)
color) {{
methods (override) turnOn
paint }}
this.color = color;
this.color = color;
class
class ElectricCar
ElectricCar extends
extends Car
Š Can add new attributes and methods
Car
void turnOn() { {{
void turnOn() {
isOn=true;
isOn=true;
}} boolean
boolean cellsAreCharged;
cellsAreCharged;
ElectricCar }} void
void recharge()
recharge() {{
cellsAreCharged
cellsAreCharged == true;
true;
cellsAreCharged }}
recharge
turnOn
void
void turnOn()
turnOn() {{
if(cellsAreCharged
if(cellsAreCharged ))
isOn=true;
isOn=true;
}}
}}
11 12
Inheritance in Java: extends ElectricCar
class
class Car
Car {{
String
ƒ Inherits
Car String color;
color;
color
boolean
boolean isOn;
String
isOn;
String licencePlate;
licencePlate;
Š attributes (color, isOn, licencePlate)
Š methods (paint)
isOn
licencePlate void
void paint(String
paint(String color)
color) {{
ƒ Modifies (overrides)
turnOn this.color
this.color == color;
color;
paint }}
class
class ElectricCar
ElectricCar extends
extends Car
Car
void turnOn() {{ {
void turnOn()
isOn=true;
{
Š turnOn()
isOn=true;
ƒ Adds
}} boolean
boolean cellsAreCharged;
cellsAreCharged;
ElectricCar }} void
void recharge() {{
recharge()
Š attributes (cellsAreCharged)
cellsAreCharged
cellsAreCharged == true;
true;
cellsAreCharged }}
recharge
turnOn
void
void turnOn()
turnOn() {{
Š Methods (recharge)
if(cellsAreCharged
if(cellsAreCharged ))
isOn=true;
isOn=true;
}}
}}
13 14

Example
class Employee {
private String name;
private double wage;
}
Visibility (scope)
class Manager extends Employee {

void print() {
System.out.println(“Manager” +
name + “ ” + wage);
}
}
Not visible
16
Protected In summary
ƒ Attributes and methods marked as Method of
Method of
another
Š public are always accessible Method in another Method
public class
the same class in the of
in the
Š private are accessible within the class class same subclass
outside
only package
world
Š protected are accessible within the class
and its subclasses
private 9
package 9 9
protected 9 9 9
public 9 9 9 9
17

Super (reference) Example


class
class Car
Car {{
ƒ “this” is a reference to the current String
String color;
object
Car color;
boolean
boolean isOn;
isOn;
color String
String licencePlate;
licencePlate;
ƒ “super” is a reference to the parent
isOn
licencePlate void
void paint(String
paint(String color)
color) {{
class turnOn
paint }}
this.color = color;
this.color = color;
class
class ElectricCar
ElectricCar extends
extends Car{
Car{
void turnOn()
void turnOn() {{
isOn=true; boolean
boolean cellsAreCharged;
cellsAreCharged;
isOn=true;
}}
ElectricCar }} void
void recharge()
recharge() {{
cellsAreCharged
cellsAreCharged == true;
true;
cellsAreCharged }}
was void
recharge
if(cellsAreCharged) void turnOn()
turnOn() {{
turnOn if(
if( cellsAreCharged
cellsAreCharged ))
isOn = true; super.turnOn();
super.turnOn();
}}
}}
19 20
Attributes redefinition
ƒ Class Parent{
protected int attr = 7;

Inheritance and
}
ƒ Class Child{
protected String attr = “hello”;

void print(){ constructors


System.out.println(super.attr);
System.out.println(attr);
}

public static void main(String args[]){


Child c = new Child();
c.print();
}
}

21

Construction of child objects Construction of child objects


ƒ Since each object “contains” an ƒ Execution of constructors proceeds
instance of the parent class, the latter top-down in the inheritance hierarchy
must be initialized
ƒ Java compiler automatically inserts a ƒ In this way, when a method of the
call to default constructor (no params) child class is executed (constructor
of parent class included), the super-class is
ƒ The call is inserted as the first completely initialized already
statement of each child constructor

23 24
Example Example (cont’d)
class
class ArtWork
ArtWork {{
ArtWork()
ArtWork() {{
System.out.println(“New Cartoon obj = new Cartoon();
System.out.println(“New ArtWork”);
ArtWork”); }}
}}

class
class Drawing
Drawing extends
extends ArtWork
ArtWork {{
Drawing() new
new ArtWork
ArtWork
Drawing() {{
System.out.println(“New
System.out.println(“New Drawing”);
Drawing”); }}
new
new Drawing
Drawing
}} new
new Cartoon
Cartoon

class
class Cartoon
Cartoon extends
extends Drawing
Drawing {{
Cartoon()
Cartoon() {{
System.out.println(“New
System.out.println(“New Cartoon”);
Cartoon”); }}
}}
25 26

A word of advice Super


ƒ Default constructor “disappears” if ƒ If you define custom constructors
custom constructors are defined with arguments
class
class Parent{
Parent{ ƒ and default constructor is not defined
explicitly
Parent(int
Parent(int i){}
i){}
}}
class
class Child
Child extends
extends Parent{
Parent{ }}
// error!
// error! class
class Parent{
Parent{ Î the compiler cannot insert the call
automatically
Parent(int
Parent(int i){}
i){}
Parent(){}
Parent(){} //explicit
//explicit default
default
}}
class
class Child
Child extends
extends Parent
Parent {{ }}
// ok!
// ok!
27 28
Super Example
ƒ Child class constructor must call the class
class Employee
Employee {{

right constructor of the parent class,


private
private String
String name;
name;
private
private double wage;
double wage;
explicitly ???
???
Employee(String
Employee(String n, n, double
double w){
w){
name
name == n;
n;
wage
wage == w;
w;
ƒ Use super() to identify constructors of }} class
class Manager
Manager extends
extends Employee
Employee {{
parent class
}} private
private int
int unit;
unit;

Manager(String
Manager(String n, n, double
double w,
w, int
int u)
u) {{
super();
super(); ERROR
ERROR !!!
!!!
ƒ First statement in child constructors
unit
unit == u;
u;
}}
}}

29 30

Example
class
class Employee
Employee {{
private
private String
String name;
name;

Dynamic binding/
private double wage;
private double wage;

polymorphism
Employee(String
Employee(String n,
n, double
double w){
w){
name
name == n;
n;
wage
wage == w;
w;
}} class
class Manager
Manager extends
extends Employee
Employee {{
}} private
private int
int unit;
unit;

Manager(String
Manager(String n,
n, double
double w,
w, int
int u)
u) {{
super(n,w);
super(n,w);
unit
unit == u;
u;
}}
}}

31
Example Binding
ƒ Car[] garage = new Car[4]; ƒ Association message/method
ƒ garage[0] = new Car(); ƒ Constraint Car

ƒ garage[1] = new ElectricCar(); Š Same signature


color
isOn

ƒ garage[2] = new ElectricCar(); licencePlate

Car a; turnOn

ƒ garage[3] = new Car(); for(int i=0; i<garage.length; i++){


paint

a = garage[i]
a.turnOn();
ƒ for(int i=0; i<garage.length; i++){ } ElectricCar

garage[i].turnOn(); cellsAreCharged

} message method recharge


turnOn

33 34

Java Object
ƒ java.lang.Object
ƒ All classes are subtypes of Object

Object
Object

extends Object Implicitly

class
class Vertebrate
Vertebrate {{
Vertebrate
hasSpine ……
}}

class
class Bird
Bird extends
extends Vertebrate{
Vertebrate{
Bird
……
canFly }}

36
Java Object Java Object
ƒ Each instance can be seen as an Object
ƒ toString()
instance (see Collection)
Š Returns a string
uniquely identifying
ƒ Object defines some services, which are the object
Object
useful for all classes
toString() : String
ƒ Often, they are overridden in sub-classes ƒ equals() equals(Object) : boolean
Š Tests equality of
Object values
toString() : String
equals(Object) : boolean

37 38

System.out.print( Object )
ƒ print methods implicitly invoke
toString() on all object parameters
class Car{ String toString(){…} }

Casting
Car c = new Car();
System.out.print(c); // same as...
... System.out.print(c.toString());
ƒ Polymorphism applies when toString() is
overridden
Object ob = c;
System.out.print(ob); // Car’s toString() is called

39
Types Specialization
ƒ Java is a strictly typed language, i.e., ƒ Things change slightly
each variable has a type
ƒ Normal case…

ƒ float f;
f = 4.7; // legal class Car{};
f = “string”; // illegal class ElectricCar extends Car{};
Car c = new Car();
ƒ Car c;
ElectricCar ec = new ElectricCar ();
c = new Car(); // legal
c = new String(); // illegal

41 42

Specialization - 2 Specialization - 3
ƒ New case… ƒ Legal!
Š Specialization defines a sub-typing
class Car{}; relationship (is a)
class ElectricCar extends Car{}; Š ElectricCar type is a subset of Car type
Car a = new ElectricCar (); // legal?? Car

Car(s)

ElectricCar(s) ElectricCar

All electric cars are cars too


43 44
Cast Upcast
ƒ Type conversion (explicit or ƒ Assignment from a more specific type
(subtype) to a more general type (supertype)
implicit) class Car{};
class ElectricCar extends Car{};
ƒ int i = 44; Car c = new ElectricCar ();
ƒ float f = i;
// implicit cast 2c -> fp ƒ Note well - reference type and object type
are separate concepts
ƒ f = (float) 44; Š Object referenced by ‘c’ continues to be of
// explicit cast ElectricCar type

45 46

Upcast Downcast
ƒ It is dependable ƒ Assignment from a more general type
Š It is always true that an electric car is a car too (super-type) to a more specific type
ƒ It is automatic (sub-type)
Š As above, reference type and object type
Car c = new Car();
ElectricCar ec = new ElectricCar (); do not change
c = ec;

ƒ MUST be explicit
Š It’s a risky operation, no automatic
ec
c
3 2
Up-casting: 1 conversion provided by the compiler (it’s
Object type does NOT change up to you!)
ElectricCar
Car

47 48
Downcast - Example I Dowcast – Example II

Car
Car cc == new
new ElectricCar();
ElectricCar(); //
// impl.
impl. upcast Car
Car cc == new
new Car();
upcast Car(); Run-time error
c.recharge();
c.recharge(); //
// wrong!
wrong! c.rechage();
c.rechage(); //
// wrong!
wrong!

//
// explicit
explicit downcast
downcast //
// explicit
explicit downcast
downcast
ElectricCar
ElectricCar ec
ec == (ElectricCar)c;
(ElectricCar)c; ElectricCar
ElectricCar ec
ec == (ElectricCar)c;
(ElectricCar)c;

ec.recharge();
ec.recharge(); //
// ok
ok ec.recharge();
ec.recharge(); //
// wrong!
wrong!

YOU know they are compatible types YOU might be wrong (risk)
(compiler trusts you)

49 50

Visually Messy example


ec2
ƒ All electric cars are cars too Car c, cc;
ElectricCar ec, ec2; c cc ec
ƒ Not all cars are electric cars are too c = new Car (); // 1 5
3
c. recharge(); // NO 2

1 4
Car
ec = new ElectricCar (); // 2
Car(s) ec.recharge() // ok
downcast ElectricCar
upcast
cc = c; // 3
Car
ElectricCar(s) ElectricCar
c= ec; // 4 Upcasting
c. recharge(); // NO

51 52
Messy example (cont’d) Avoid wrong down-casting
ec2
ec2 = c; // NO Downcast
ƒ Use the instanceof operator
ec2 = (ElectricCar) c; // 5, OK cc
ec2. recharge(); // OK 5
3
ƒ Car c = new Car();
ec2 = (ElectricCar ) cc ; // 6 6
ElectricCar ec;
ec2.recharge(); // runtime error

ElectricCar if (c instanceof ElectricCar ){


Car ec = (ElectricCar) c;
ec.recharge();
}
was
((ElectricCar)c).recharge();

53 54

Upcast to Object
ƒ Each class is either directly or
indirectly a subclass of Object
ƒ It is always possible to upcast any
instance to Object type (see Abstract classes
Collection)
AnyClass foo = new AnyClass();
Object obj;
obj = foo;

55
Abstract class Abstract modifier
ƒ Often, superclass is used to define public
public abstract
abstract class
class Shape
Shape {{
common behavior for many child
classes
privte
privte int
int color;
color;

ƒ But the class is too general to be public


public void
void setColor(int
setColor(int color){
this.color
color){
this.color == color;
instantiated
color;
}}
ƒ Behavior is partially left unspecified //
// to
to be
be implemented
implemented in
in child
child classes
classes
(this is more concrete than interface) public
public abstract
abstract void
void draw();
draw();
}}
No
method
body

57 58

Abstract modifier

public
public class
class Circle
Circle extends
extends Shape
Shape {{
public
public void
void draw()
draw() {{
}}
//
// body goes here
body goes here Interface
}}

Object
Object aa == new
new Shape();
Shape(); //
// Illegal
Illegal
Object
Object aa == new
new Circle();
Circle(); //
// OK
OK

59
Java interface Example
ƒ An interface is a special type of “class” <<interface>>
Comparable
where methods and attributes are
isEqual(String) : boolean
implicitly public
Š Attributes are implicitly static and final
Š Methods are implicitly abstract (no body) Car Employee

String licencePlate String name


ƒ Cannot be instantiated (no new) isEqual(String) : isEqual(String) :
boolean boolean
ƒ Can be used to define references

61 62

Example (cont’d) Example


public
public interface
interface Comparable
Comparable {{ public
void public class
class Foo
Foo {{
void isEqual(String
isEqual(String s);
s); private
private Comparable objects[];
Comparable objects[];
}} public
public Foo(){
Foo(){
Public
Public objects
objects == new
new Comparable[3];
Comparable[3];
objects[0]
objects[0] == new
new Employee();
Employee();
public
public class
class Car
Car implements
implements Comparable
Comparable {{ objects[1]
private String licencePlate; objects[1] == new
new Car();
Car();
private String licencePlate; objects[2]
objects[2] == new
new Employee();
Employee();
public
public void
void isEqual(String
isEqual(String s){
s){ }}
return licencePlate.equals(s);
return licencePlate.equals(s); public
}} public Comparable
Comparable find(String
find(String s){
s){
for(int
for(int i=0; i< objects.length; i++)
i=0; i< objects.length; i++)
}} public
public class
class Employee
Employee implements
implements Comparable{
Comparable{ if(objects[i].isEqual(s)
private String name; if(objects[i].isEqual(s)
private String name; return
return objects[i];
objects[i];
public
public void
void isEqual(String
isEqual(String s){
s){ }}
return name.equals(s);
return name.equals(s); }}
}}
}}
63 64
Rules (interface) Rules (class)
ƒ An interface can extend another ƒ A class can extend only one class
interface, cannot extend a class ƒ A class can implement multiple
interface Bar extends Comparable {
interfaces
void print();
} interface

ƒ An interface can extend multiple class Person


interfaces extends Employee
implements Orderable, Comparable {…}
interface Bar extends Orderable,
Comparable{
...
interfaces
}

65 66

A word of advice Homework


ƒ Defining a class that contains abstract
ƒ See the doc of java.lang.Comparable
methods only is not illegal
Š You should use interfaces instead
public interface Comparable{
ƒ Overriding methods in subclasses can
int compareTo(Object obj);
maintain or extend the visibility of
}
overridden superclass’s methods
Š e.g. protected int m() can’t be overridden by
ƒ Returns a negative integer, 0, or a
– private int m()
positive integer as this object is less
– int m()
than, equal, or greater than obj
Š Only protected or public are allowed
67 68
Homework (cont’d) Homework (cont’d)
ƒ Define Employee, which implements public static void main(String args[]){
Comparable (order by ID) int size = 3; // array size
OrderedArray oa = new OrderedArray(size);
ƒ Define OrderedArray class
oa.add( new Employee(“Mark”, 37645) );
Š void add(Comparable c) //ordered insert oa.add( new Employee(“Andrew”, 12345) );
Š void print() //prints out oa.add( new Employee(“Sara”, 97563) );

oa.print(); Name ID
ƒ Test it with the following main }

69 70

Wrap-up session Wrap-up session


ƒ Inheritance ƒ Polymorphism
Š Objects defined as sub-types of already existing
objects. They share the parent data/methods Š The same message can produce different
without having to re-implement behavior depending on the actual type of
ƒ Specialization the receiver objects (late binding of
Š Child class augments parent (e.g. adds an message/method)
attribute/method)
ƒ Overriding
Š Child class redefines parent method
ƒ Implementation/reification
Š Child class provides the actual behaviour of a
parent method
Wrap-up session
ƒ Polymorphism
Š The same message can produce different
behavior depending on the actual type of
the receiver objects (late binding of
message/method)

You might also like