This question already has an answer here:
I've faced a very curious question in my last work with Java. I want an attribute of the superclass to be accessed only by the class itself and it's daughters. As you know, nor private neither protected modifier offers me this solution. So I've declared the same attribute at both the parent and the daughter class.
But it took me to strange paths. Here's an example:
public class Father{
private int variable = 0;
void showVariable(){
System.out.print(variable);
}
}
class daughter extends Father{
private int variable = 5;
void showDaugtherVariable(){
System.out.println(variable);
}
}
class main{
public static void main(String[] args){
daughter daughter = new daughter();
daughter.showDaugtherVariable();
daughter.showVariable();
}
}
What is printed:
5
0
As you see, I can work with variable as I want. It seems that I've succesfully overwrited it. But if I work with it with a superclass method, It uses the superclass value...as if it was keeping two variables with the same name for the daughter class, one of them inherited by the father.
Why this behavior?
Aucun commentaire:
Enregistrer un commentaire