I am new to Java and am working on an inheritance demo. I am puzzled because when I attempt to access the private field of the superclass with name
or this.name
, the compiler correctly reports an error as many toturials told that subclass have no access to private field in superclass. However, when I use super.name
, there are no errors, and calling this method seems to update the name
field in the subclass object.
I am using IDEA with jdk 18, and the full code of my demo is shown below
public class IV_extend_class_ver2 {
public static class Person {
//field
private String name = "Person";
//default Constructor
//method
public String getName(){ return this.name; }
public void setName(String name){ this.name = name; }
}
//Worker extends from Person
public static class Worker extends Person {
private int salary;
public int getSalary() { return this.salary; }
public void setSalary(int salary) { this.salary = salary; }
//access the private member in superclass
public String hello() {
return "Hello, " + super.name;
// If write name or this.name, an error would get in IDEA
// But if I wirte super.name,it compiles successfully
// and if I call hello() in next part, it works
}
}
public static void main(String[] args) {
Worker man = new Worker();
System.out.println(man.hello());
man.setName("Bob");
System.out.println(man.hello());
}
}
and the results would be
Hello, Person
Hello, Bob
Thanks
Could someone explain why this is happening? I am confused about two things:
- Why does
super.name
work in this program? - Why it’s the
name
field of the subclass changes rather than the superclass, assuper
should imply?