Junior
How does a subclass use the functionality of its parent class?
sobes.tech AI
Answer from AI
Through inheritance: a derived class receives the public and protected members of the parent class.
- Direct access: Public and protected fields and methods of the parent can be accessed directly by their name within the derived class.
superkeyword: Used to call the parent's constructor or to access overridden methods/fields of the parent when the derived class has members with the same name.- Overriding: Parent methods (not
final) can be overridden in the derived class, changing their behavior.
// Example of a parent class
class Parent {
protected int parentValue;
public Parent(int value) {
this.parentValue = value;
}
public void displayParentValue() {
System.out.println("Parent value: " + parentValue);
}
public final void cannotBeOverridden() {
System.out.println("This method cannot be overridden.");
}
}
// Example of a derived class
class Child extends Parent {
private int childValue;
public Child(int parentValue, int childValue) {
super(parentValue); // Call to the parent's constructor
this.childValue = childValue;
}
// Overriding the parent's method
@Override
public void displayParentValue() {
System.out.println("Overridden parent value: " + parentValue); // Access to the parent's protected field
}
public void displayChildValue() {
System.out.println("Child value: " + childValue);
}
public void callParentMethod() {
super.displayParentValue(); // Call to the parent's method via super
}
}