Inheritance Flashcards
the class that inherits from another class
Subclass (child)
the class being inherited from
Superclass (parent)
What keyword is use to inherit from a class?
extends
It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
Inheritance
Which class is the subclass (child) and the superclass (parent) in the following code?
class Vehicle {
protected String brand = “Ford”; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println(“Tuut, tuut!”);
}
}
class Car extends Vehicle {
private String modelName = “Mustang”; // Car attribute
public static void main(String[] args) {
// Create a myCar object Car myCar = new Car(); // Call the honk() method (from the Vehicle class) on the myCar object myCar.honk(); // Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class System.out.println(myCar.brand + " " + myCar.modelName); } }
Vehicle - superclass (parent)
Car - subclass (child)
If you don’t want other classes to inherit from a class, what keyword must be used?
final
What will happen in the following code?
final class Vehicle {
…
}
class Car extends Vehicle {
…
}
Java will generate an error when you try to access a final class
used to have general class to specific class by using the word extends
Inheritance
Which class is the subclass (child) and superclass (parent) below?
class A {
…
}
class B extends A {
…
}
Class A - Superclass/Parent
Class B - Subclass/Child