Professional Documents
Culture Documents
What is inheritance
8: Inheritance
Defining a Subclass
A.java
public class A
{
...
}
B.java
}
public class Lion extends Cat
{ //Override the kick behaviour
public void kick(){
System.out.println(RoooAAARRWW!);
}
}
//Lion also inherits the stroke method
continued...
Points to note
Object
Person
Circle
Cylinder
Student
Employee
Lecturer
Secretary
method overriding.
Car
BlueCar
RedCar
GreenCar
distahead=0;
}
else distahead++;
}
//Add a new car to road
if ( road[0]==null && r<arrivalprob )
road[0] = getNewCar();
}
}
}
}
Casting objects
It is always possible to convert a subclass to a
superclass. In this case, explicit casting can be omitted.
For example,
Circle myCircle = myCylinder
is equivalent to
Casting from
superclass to subclass
Explicit casting must be used when casting an object
from a superclass to a subclass. This type of casting
may not always succeed.
Cylinder myCylinder = (Cylinder)myCircle;
Polymorphism
Polymorphism (or generic programming) is a technique
that allows a single piece of code to be reusable with
many different types.
Cat clarence = new Cat();
if (Math.random>0.5)
Polymorphism - Example
Object[] myobjects = new Object[4];
//Fill the array with objects
myobjects[0] = new Fraction(3,4);
myobjects[1] = new Employee();
myobjects[2] = new Cylinder();
myobjects[3] = Java;
Polymorphism - Example
public static void printArray(Object[] objects)
{
for (int i=0; i<objects.length; i++)
{
Object o = objects[i];
System.out.print(Item at + i + :);
if (o==null)
System.out.println(null);
else
System.out.println( o.toString() );
}
}
its subclasses.
public final void update(int d);
Boolean
Constructors
Character
Short
Byte
Integer
Conversion methods
Long
Float
Double
Multiple inheritance?
Interfaces
class
"extends"
"implements"
interface
Comparable
class
Geometric
class
Comparable
interface
Geometric
class
Circle
Cylinder
Circle
Comparable
circle
Cylinder
Comparable
cylinder
Comparable
circle
An interface
Using interfaces
Comparable
cylinder