05 JavaInheritance
05 JavaInheritance
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
Parent class
Class one below
Animal vegetal
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;
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
Inheritance and
}
Class Child{
protected String attr = “hello”;
21
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
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
Car a; turnOn
a = garage[i]
a.turnOn();
for(int i=0; i<garage.length; i++){ } ElectricCar
garage[i].turnOn(); cellsAreCharged
33 34
Java Object
java.lang.Object
All classes are subtypes of Object
Object
Object
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
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
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
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;
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
61 62
65 66
oa.print(); Name ID
Test it with the following main }
69 70