AP CSA Inheritance
AP CSA Inheritance
Inheritance
The subclass can have its own specific methods and variables
Using subclasses prevents repetition
Special rules:
A subclass can only inherit from one superclass (called the diamond problem)
Making a subclass
To make a subclass: “public class insert subclass name extends insert super class name”
Ex: public class X extends Y
Constructors
Constructors are not inherited from superclasses
To use a constructor from a superclass, you can call the constructor implicitly or explicitly
The super keyword (explicit)
super is a constructor
It lets you use the constructor of the superclass with the parameters of the
subclass
Instance variables are initialized
This is especially useful when you want to do the same thing the
superclass does but with different input variables
This assumes you’re not changing anything about the
implementation of the superclass’s method
public class firstClass {
int x = 1;
}
When a public method from the subclass has the same method signature as a public
method from the superclass
Method signature: the combination of the method’s name and its parameters
(order of parameters does matter!!)
Subclasses automatically inherit all public methods from the superclass (these methods
stay public)
@Override is used to indicate that the method directly below it overrides a method
from a superclass (@Override is an annotation)
public class firstClass {
public String rand() {
return “banana”;
}
@Override
public class secClass extends firstClass {
public String rand() {
return “apple”;
}
}
Using inheritance hierarchies
We often overwrite or modify the methods from the Object class (like equals() or toString())