You are on page 1of 8

AP Computer Science Lesson 9

Intro to Object Oriented Programming Ctd.


Subclasses, Inheritance, and Polymorphism

Classes and Subclasses

Same relationships as sets and subsets in math

Integers Real Numbers

Dogs Animals

Dogs share some properties with all animals


despite having their own attributes
In order to allow for code re-usability, the dog
class can inherit the animal properties by being
a subclass of animal.

Subclass Example

Public class Animal{


double weight; int numLegs;
public void speak(){
System.out.println(I am an animal.);

This is the animal class that the dog class will


inherit from

Subclass Example ctd.

Public class Dog extends Animal{


String breed;
//constructor here
public void speak(){
System.out.println(Woof. I am a dog.);

The Dog will a breed in addition to numLegs


and weight from Animal
When speak() is called, Woof. I am a dog is
displayed. This is called method overriding.

Polymorphism

Declaring a dog can be done in different ways

Dog dog1 = new Dog(); //dog object

Animal dog2 = new Dog(); //dog object

Object dog3 = new Dog(); //dog object

Dog dog4 = new Animal(); //error

Animal a1 = new Animal(); //animal object

Polymorphism <is-a>

Animal a = new Dog();

The variable a is declared to point to an animal

A dog is an animal, thus we can have a point to


the dog
The relationship between a class and its
subclass is an is-a relationship

Dog is an Animal

Polymorphism ctd.

Polymorphism is useful for storing different


types of objects in the same structure
Ex: consider a car dealership storing different
types of cars in an ArrayList called lot2

Types are sedan, truck, and SUV

ArrayList<Car> lot2 = new ArrayList<Car>();

lot2.add(new sedan(Honda Civic 09));

lot2.add(new SUV(Nissan Pathfinder 05));

Multiple Inheritance

Classes can have many levels of inheritance


Integers are in the set of real number which are
in the set of complex numbers

Humans are mammals which are animals

Java allows for multiple inheritance

Same rules apply for single inheritance

Be mindful of its application

You might also like