Inheritance
Inheritance Hierarchies and Design
Inheritance- A way to create a relationship amongst classes.
Inheritance Hierarchy- A way to determine how information travels amongst the classes. Ex: The subclasses inherit characteristics of the parent class.
The parent class is referred to as the superclass, and the classes that inherit from it are referred to as subclasses of the superclass.
The parent class is the most general form of the objects that will be instantiated in the program.
In Java, the topmost superclass is called the Object class.
All the other classes in the program will lie lower in the hierarchy, but they will be more specific compared to the parent class.
Let’s think of inheritance using an example, it’s the easiest way to explain this concept.
Ex: Say you want to buy something, and you decide to buy a snack. Then you wonder which type of snack should I get. You narrow it down to potato chips and cookies. However, there are 2 types of potato chips(Classic, and BBQ), and 2 types of Cookies(Chocolate Chip, and Macadamia Nut.)
In the example above each of the different snack items is divided up into their own specific categories, and is like a hierarchy because one thing follows the other.
Note: On the AP Exam there is at least 1 free-response question and many multiple-choice questions that focus on the design and implementation of inheritance relationships.
Important!!- Classes inherit public variables and public methods from their superclasses!
Overridden method- When one version of a method is replaced by another version.
Write a subclass with the format
public class Subclass extends Superclassas the class headerThe phrase
super()is a constructor for the superclass built into the subclass. This allows the subclass to use code from the superclass constructor, such as to initialize private instance variables of the superclass. Essentially, it calls the constructor of the superclass. It must be the very first line of the subclass constructor.Polymorphism
Polymorphism- When many classes are related to each other by inheritance. Inheritance lets us inherit attributes and methods from another class. Polymorphism uses those methods to perform different tasks.
Ex: Let’s look at a class that will be used to represent a rectangle with the concepts we just learned.
public class Rectangle
{
private double width;
private double height;
public Rectangle()
{
width = w;
height = 0;
}
public Rectangle(double w, double h)
{
width = w;
height = h;
}
public double getHeight()
{
return height;
}
public double getWidth()
{
return width;
}
}Ex: What output will this line of code produce?
class Animal { void someSound() { System.out.println(“Screech”); } } class Cat extends Animal { public Cat () { System.out.print(“Meow”); super.someSound(); } } class Garfield extends Cat { public Garfield() { System.out.print(“Lasagna”); } } public class Mainclass { public static void main(String [ ]args) { Garfield garfield = new Garfield(); } }