public static class DomesticAnimal {
private int weight;
private int age;
public int getWeight() {
return this.weight;
}
}
public static class Chicken extends DomesticAnimal {
public int wings;
public void setWeight() {
this.weight = 5; // error! weight has private access in DomesticAnimal
}
}
Class "Chicken" inherits the variables from the class Domestic Animal.
I would think it means the Chicken class (and its object) has the own "private weight" variable. This variable is inherited, so this should exist in a Chicken-object, too.
But in the Chicken class i can't access my own weight variable.
Or is it not completely my own variable here, = not inherited 100% completely, is it only some type of borrow? With more narrow rights.
(Yes, i know, move the setWeight() method into the parent-class, and it will work. But my question is not this here.)
Thanks!:)Question about inherited private variable
Resolved
Comments (4)
- Popular
- New
- Old
You must be signed in to leave a comment
Nouser
8 January 2021, 18:49
private: only the class itself has access
package private: the class and all classes inside the same package have access
protected: class, package and subclassess have access. So if your child is not in the same package you'll have to chose this
Or use public/ protected setters, getters
+1
Gellert Varga
8 January 2021, 19:08
Yes i know the modifiers theoretically...
I just got confused in the concept of inheriting.
Private: does it mean , it can be used only in the class where it was declared? Even the inheritor must not use it.
0
Nouser
8 January 2021, 20:02solution
yes, exactly.That way the class programmer can force other coders who extend that class to use just the constructor and / or setters (that's also encapsulation)
+3
Gellert Varga
8 January 2021, 20:30
OK, thanks!:)
0