r/learndota2 • u/SlowerPhoton • Oct 14 '16
All Time Top Post [Java] How does inheritance really work?
I have a following class:
public class Parent {
private int number;
// more stuff
}And another, which inherits from Parent:
public class Child extends Parent {
public void setNumber(int newNum){
this.number = newNum;
}
}I always thought Child was a copy of Parent, but you could add stuff to it (and possibly change something). So I would expect it already has the 'number' attribute. However this will never compile as there isn't anything named like that. Why?
EDIT: I am sorry, guys. I thought this was /r/learnprogramming. I don't play dota and I am not even subscribed so this is a mystery to me.
2.8k
Upvotes
5
u/Licheus Oct 15 '16 edited Oct 15 '16
Each instance will always have its own number. That's the point: you create a new unique entity; a new object, with the "new" keyword. Every new Child object you create will have an own unique number in their Parent component.
private, protected or public just tells you if you can see ("access") number from Parent through the Child object. If number is private, you cannot see number when working with the Child object. But number still exists privately in Parent, tucked away from the world forever with no hopes of ever seeing the sun.