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

21

u/TheGrammarBolshevik Oct 15 '16

public = Can be accessed by anyone, any class.
Good for global things like numberOfHumansInWorld and listOfEveryNode.
Bad for secret things like myBankAccount and nukeLaunchCodes.

This might be OK as a metaphor, but access modifiers aren't really about security. The point is to keep your code maintainable by limiting the extent to which clients can depend on the details of your implementation.

If you're distributing nuke launch codes inside a Java class, marking them as private isn't going to save you.

4

u/fritzvonamerika Oct 15 '16

It helps a little to think it's a security thing. You don't want someone to write

nukeLaunchCode = "6969lulz";

and actually overwrite the value it needs to be. The security is managing who can read and write to the fields of a class which isn't the same as encryption, but still a form of security

1

u/Krossfireo Oct 16 '16

Another important point is that with Java reflection, it doesn't even give security since you can crack those classes right open