Sobes.tech
Junior — Middle

How can a subclass access methods or properties of the base class?

sobes.tech AI

Answer from AI

In Java, from a subclass, you can directly access methods or properties of the superclass if they are accessible (for example, if they have the access modifier protected or public). If you need to explicitly specify that a method or property of the superclass is being called, the keyword super is used.

Example:

class Base {
    int value = 10;
    void show() {
        System.out.println("Base show: " + value);
    }
}

class Derived extends Base {
    int value = 20;
    void show() {
        System.out.println("Derived show: " + value);
        System.out.println("Base value via super: " + super.value);
        super.show();
    }
}

public class Test {
    public static void main(String[] args) {
        Derived d = new Derived();
        d.show();
    }
}

Here, super.value and super.show() refer to the field and method of the superclass.

How can a subclass access methods or properties of… - sobes.tech