CSE/IT 213 - Inheritance and Polymorphism: New Mexico Tech
CSE/IT 213 - Inheritance and Polymorphism: New Mexico Tech
Polymorphism
New Mexico Tech
September 16, 2011
class Bicycle {
public float tireSize;
public setBrakeType();
}
class RoadBike extends Bicycle {
//inherits tireSize
//inherits setBrakeType();
private int gears;
public void setGear();
}
Public ivars
Declaring ivars as public breaks encapsulation.
While you inherit ivars, in practice they are declared
private and are not directly accessible in subclasses
Use the parent classes getter/setter methods to access
ivars.
Overloading methods
methods with the same name but different number or
type of arguments
Signature of method = name and argument types
subclasses can overload inherited methods
Constructors are commonly overloaded
Overloading occurs at compile time
Overriding methods
Subclasses can define methods that have the exact
same signature as a method in a superclass
the sublcass method is said to override the method of
the superclass
overriding replaces the implementation of the method
Called subtype polymorphism
class Bicycle {
setGear()
}
class RoadBike {
setGear()
}
....
RoadBike road = new RoadBike();
Bicycle bike = new RoadBike();
bike.setGear(); //accesses RoadBikes setGear()
10
So What?
Behavior of objects is dynamic
Can treat specialized objects as more general types of
objects while still taking advantage of their specialized
behaviors
Dynamic Binding the behavior of objects is determined at run-time
12
class Animal
$ java Animal
The animals are sleeping
Pig is sleeping
Horse is sleeping
Dog is sleeping
15
16
class Animal
18
19
$ java Animal
The animals are sleeping
animals eat everything
Pig is sleeping
pigs eat slop
Horse is sleeping
horses love hay
Dog is sleeping
dog eat dog food
20
21
Dog()
Mammal()
Dog()
Animal()
Mammal()
Dog()
Object()
Animal()
Mammal()
Dog()
super keyword
Allows methods of subclasses to call the parent class
class Bicycle {
public setGear() {
....
}
}
class RoadBike extends Bicycle {
public setRatio() {
//this wont work
//setGears not defined in RoadBike
gears = setGears()
}
}
24
super as a constructor
If super is the first line of a constructor, the parents
constructor is called.
By calling your parents class constructor, you can set
the private ivars of your parents class.
26
28
class OnRun {
private int size;
public void setSize(int size) {
this.size = size;
}
public int getSize() {
return this.size;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
OnRun s = new OnRun();
System.out.println("enter size of array");
s.setSize(in.nextInt());
int [] aInt = new int[s.getSize()];
29