r/learndota2 • • 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

245 comments sorted by

View all comments

Show parent comments

13

u/submarine_golfcart Oct 15 '16

Always remember: you can't touch your parent's privates!

2

u/Matrix_V Oct 16 '16

The same is true in C++, but you can access your friends' privates.

Fun fact.

Okay, I'll go.

1

u/lennybird Oct 16 '16

But inheritance does allow direct access to the methods, and if you're doing it right, you've got getters & setters through which you can access private member variables.