You are on page 1of 38

CSE/IT 213 - Inheritance and

Polymorphism
New Mexico Tech
September 16, 2011

Subclassing and Inheritance


Subclasses inherit instance variables (ivars) and methods from its super class
Can use methods and ivars as if they were declared in
the subclass.
To declare a class a subclass of another class use the
extends keyword

In javadoc inheritance is defined at the top of the documentation.


java.util
Class GregorianCalendar
java.lang.Object
-java.util.Calendar
-java.util.GregorianCalendar

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

Can use @override marker to tell the compiler you are


overriding a method.
Compiler will give a warning if the methods dont match.
Good practice to use.

When there are multiple implementations of a method


in the inheritance hierarchy of an object, the method
in the lowest class of the hierarchy always overrides all
others.
The most-derived method is the one that is executed.
This behavior holds even if we refer to the object through
a reference to its superclass

class Bicycle {
setGear()
}
class RoadBike {
setGear()
}
....
RoadBike road = new RoadBike();
Bicycle bike = new RoadBike();
bike.setGear(); //accesses RoadBikes setGear()

What is happening here?


RoadBike road = new RoadBike()
1) creates a reference named road, RoadBike road
2) creates an object new RoadBike()
3) assigns = the reference to point to the object.
The reference type and the object type are the same.

10

Bicycle bike = new RoadBike();


The reference type and the object type are NOT the
same.
This is polymorphism
Anything that extends the reference type can be assigned to the reference variable.
There is an IS-A relationship between the object and
the reference
Polymorphism allows the reference type and object type
to be different.
11

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

public void sleep() {


System.out.println("The animals are sleeping");
}
public static void main(String[] args) {
Animal [] animalFarm = new Animal[4];
animalFarm[0] = new Animal();
animalFarm[1] = new Pig();
animalFarm[2] = new Horse();
animalFarm[3] = new Dog();
13

for ( Animal a : animalFarm) {


a.sleep();
}
}
}
class Dog extends Animal {
public void sleep() {
System.out.println("Dog is sleeping");
}
}

class Pig extends Animal {


public void sleep() {
System.out.println("Pig is sleeping");
}
}
class Horse extends Animal {
public void sleep() {
System.out.println("Horse is sleeping");
}
}
14

$ java Animal
The animals are sleeping
Pig is sleeping
Horse is sleeping
Dog is sleeping

15

Loops through array animalFarm and calls the Animal


sleep method, but knows how to call the right subclass
method.
Allows you to write flexible code
Can also have polymorphic argument types

16

class Animal

public void sleep() {


System.out.println("The animals are sleeping");
}
public static void main(String[] args) {
Animal [] animalFarm = new Animal[4];
animalFarm[0] = new Animal();
animalFarm[1] = new Pig();
animalFarm[2] = new Horse();
animalFarm[3] = new Dog();
Food food = new Food;
17

for ( Animal a : animalFarm) {


a.sleep();
food.getFood(a);
}
}
}
class Food {
public void getFood(Animal a) {
System.out.println(a.getFood());
}
}

class Dog extends Animal {


public void sleep() {
System.out.println("Dog is sleeping");
}
public String getFood() {
return "dog eat dog food";
}
}

class Pig extends Animal {


public void sleep() {
System.out.println("Pig is sleeping");
}
public String getFood() {
return "pigs eat slop";
}

18

class Horse extends Animal {


public void sleep() {
System.out.println("Horse is sleeping");
}
public String getFood() {
return "horses love hay";
}

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

Any class that extends Animal would also work in the


Food class.
This means you can write code for objects that dont
exist. When you write them just make sure they inherit
your parent class or extends your parent class.
This is only the beginning....

21

Inheritance and Constructors


All constructors of the inheritance chain are called
public class Animal {
public Animal() {
....
}
}
public class Mammal extends Animal {
public Mammal() {
....
}
}
22

public class Dog extends Mammal {


public Dog() {
...
}
}
public class MakeADog {
public static void main (String[] args) {
Dog dog = new Dog();
//calls Dog(),
//which in turn calls Mammal()
//which in turn calls Animal()
//which calls Object()
}
}

Constructors are pushed onto a stack

Dog()

Mammal()
Dog()

Animal()
Mammal()
Dog()

Object()
Animal()
Mammal()
Dog()

Once all constructors are called they are popped off


and initialization and constructor code is run for each
object
If no explicit calls to a superclass constructor is made,
a call to the superclass default (no-arg) constructor is
made
23

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

Have to use the super keyword to call the parent class


class Bicycle {
public setGear() {
....
}
}
class RoadBike extends Bicycle {
public setRatio() {
//this works calls the parent class
gears = super.setGears()
}
}
25

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

YAM - yet another modifier


Declaring a method or instance variable protected allows only subclasses of the class access to the method
or ivars.
Dont use protected on ivars. Defeats the purpose of
data encapsulation. Would allow users of your class
direct access to instance variables.
For methods, can limit access to only those classes
that extend the class. Useful if a method is difficult to
implement and use of it would depend on an existence
of a subclass.
27

Generic Array Lists


In C have to fix array sizes at compile time.
To get around the problem of figuring out how much
storage you need, you can use linked lists, etc.
Java allows you to declare array size at runtime
he ArrayList class is similar to an array, but it automatically adjusts its capacity as you add and remove
elements, without your needing to write any code.

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

for (int j = 0; j < aInt.length; j++)


System.out.println(aInt[j]);
}
$ java OnRun
enter size of array
6
0
0
0
0
0
0

In Java even better way.


Use the ArrayList class
Similar to arrays, but the class automatically adjusts its
capacity as you add and remove objects.
ArrayList is a generic class with a type parameter (more
on generics later).
ArrayList managse an internal array of object references.
To specify the type of the element objects that the
array list holds, you append a class name enclosed in
angle brackets
30

ArrayList<Animal> animal = new ArrayList<Animal>()


Use add() to add elements to the ArrayList
Use remove() to remove items from ArrayList
Size is automatically adjusted.
You can allocate initial size with the ensureCapacity
method.
animal.ensureCapacity(100) would guarantee space is
allocated for the first 100 objects.

After that, if ArrayList is full, then adding something to


the ArrayList causes ArrayList to create a larger array
and copy the old ArrayList into the new one.
This is called reallocation

You might also like