Inheritance and polymorphism allows for code reuse (not rewriting the same code more than once).
The demonstration below focuses on the aspects of inheritance and polymorphism covered on the AP CS A Exam. The material is accurate; however, some precision has been sacrificed in exchange for ease of understanding.
Java files for each class are linked below.
Pet
class
public class Pet
{
private String name;
public Pet(String pName)
{
name = pName;
}
public String getName()
{
return name;
}
public String toString()
{
return "My pet " + name;
}
}
All pets have a name, so the functionality related to name is in Pet
. Functionality that is shared or common belongs in a superclass. Pet
will be used as a superclass.
Dog
class
public class Dog extends Pet
{
private String breed;
public Dog(String dName, String breed)
{
super(dName);
this.breed = breed;
}
public String getBreed()
{
return breed;
}
public String toString()
{
return super.toString() + " is a dog";
}
}
Dog
is a subclass of Pet
. A subclass contains functionality that is new or different from its superclass.
For more about writing a subclass, calling a superclass constructor, and calling superclass methods, see Dog class details.
Cat
class
public class Cat extends Pet
{
private Color color;
public Cat(Color color)
{
super("Kitty");
this.color = color;
}
public Color getColor()
{
return color;
}
}
Cat
is a simple class similar to Dog
. Cat
does not override any methods of Pet
.
Inheritance exercise
The code below appears in a client class (a class other than Pet
, Dog
, and Cat
).
Pet p = new Cat(Color.BLACK);
System.out.println(p.getName()); // line 1
System.out.println(p.getBreed()); // line 2
System.out.println(p.getColor()); // line 3
System.out.println(p.toString()); // line 4
System.out.println(p); // line 5
For each labeled line:
- Does the line compile without error?
- If the line compiles, which method is run?
Polymorphism exercise
Pet p = new Cat(Color.BLACK);
if(Math.random() < 0.5)
p = new Dog("Clifford", "Big Red");
System.out.println(p.getName()); // line 1
System.out.println(p.getBreed()); // line 2
System.out.println(p.getColor()); // line 3
System.out.println(p.toString()); // line 4
System.out.println(p); // line 5
For each labeled line:
- Does the line compile without error?
- If the line compiles, which method is run?
Polymorphism exercise solution
Polymorphism with array exercise
Pet[] pets = new Pet[2];
pets[0] = new Cat(Color.ORANGE);
pets[1] = new Dog("Snoopy", "Beagle");
System.out.println(pets[0].getName()); // line 1
System.out.println(pets[0].getColor()); // line 2
System.out.println(pets[1].getBreed()); // line 3
System.out.println(pets[0].toString()); // line 4
System.out.println(pets[1].toString()); // line 5
For each labeled line:
- Does the line compile without error?
- If the line compiles, which method is run?
Polymorphism with array exercise solution
Review the inheritance & polymorphism exercises with AP CS Tutor Brandon Horn.