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.name);
}
}
- the output 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? **
CodePudding user response:
This is basically an issue of scoping. private
variables are only accessible to the defining class. In your case, the base class is responsible for the implementation of the getter function, and it will only know about its own variables.
The base class can't know about variables defined in subclasses (this is arguably an oversimplification, as are some explanatory details in suggestions below, but should at least get you on the right path).
If you want the subclasses to be able to modify the variable value, instead of just the function, then you would need to one of the following:
- Make the variable
protected
(visible only to the class and subclasses), and assign it in the constructor of the subclass. or, - Expose a setter function in your base class, and invoke it in your constructor. This can be protected, if you want to limit access to subclasses and not allow classes outside of the package to modify it. or,
- Simply override the getter function in your subclass. (Also, if you don't need the variable to be mutable, you can simply
return "teacher";
)
CodePudding user response:
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());
}
}