inhaler inhaler - 11 months ago 49
Java Question

Accessing the properties of a super-class from an instance of its sub-class

class Person {
public String name;
String id;

public Person() {
System.out.println("Parent default");
name = id = "";

public Person(String name, String id) {
System.out.println("Parent parameter"); = name; = id;

void show() {
System.out.println( + "\n" +;

class Student extends Person {

Student() {}

Student(String a, String b) {
super(a, b);

class Main {
public static void main(String args[]) {
Person p = new Person("A", "AA");
Student s = new Student("b", "BB");;

I'm very new to java, so I wanted to understand a few basic things, but I failed. If I inherit from a parent class, this means I get a copy of the parent class in the child class, right? So, in this code—if I reference the parent class'
method (in Main class), this is supposed to show the parent class'
which were set previously.

But it isn't showing—so I have a problem in my understanding for sure. How can I access the parent class' copy from the child class? Using the
method from child's constructor? I also want to know the basic of inheritance in short.

Answer Source

Your child class, 'Student' has inherited the show method from the parent.

Hence, when you created an object of student, with some values b and BB, those values got displayed.

The values of the student , will be passed through student to parent since you called super(a,b) and will be displayed using the show() method which is obtained from it's parent class.

Hope this helps you.