Search code examples
javaobjectmethodssubclassextends

JAVA: what happend when i call a getter method of a object which actually extend the method from it's superClass


i have two class

public class Person {
    public String name = "person";
    public String getName(){
      return name;
    };
}

public class Teacher extends Person{
    public String name ="teacher";

    public static void main(String[] args) {
        Teacher teacher = new Teacher();
        System.out.println(teacher.getName());
    }
}

  1. the output of the code teacher.getName() is "person" why?

**not matter the modify of the name property is private or public the result always is "person" but what i learn so far told me that if a subclass extends from a superClass it also entends the methods from superClass so when i call the method of subclass object, the name in method should be this.name and this should be teacher right?,but why i still get the name of superClass? **


Solution

  • The variable named name in your subclass hides the variable with the same name in the super class. See https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#d5e12172

    You probably want to have only one field name, in the superclass, and want to set it when the object is constructed:

    class Person {
        private final String name;
    
        public Person(String name) {
            this.name = name;
        }
    
        public String getName() {
            return this.name;
        }
    }
    
    
    class Teacher extends Person {
        public Teacher(String name) {
            super(name);
        }
    
        public static void main(String[] args) {
            Teacher teacher = new Teacher("teacher");
            System.out.println(teacher.getName());
        }
    }