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

3.3k

u/fuxorfly Oct 14 '16

If its private, you can't access it from derived classes; change the variable to be 'protected', and you can modify the variable from derived classes.

EDIT - also, this is the dota subreddit, you might be better off in the java sub ;)

1.8k

u/SlowerPhoton Oct 14 '16

OMG, you are right! I don't even play dota! How the fuck this happened?!

3.5k

u/ProfessorMonocle Oct 15 '16

public class java extends learndota2

56

u/GroggyOtter Oct 15 '16

I hate java and I'm not a DOTA player, but I loved this post.

22

u/TheDrGoo Old School Oct 15 '16

Sums up this whole situation pretty well I think.

→ More replies (1)

366

u/Bosticles Oct 15 '16 edited Jul 02 '23

plucky deer rob future complete cover bedroom sable snow price -- mass edited with redact.dev

→ More replies (120)

85

u/Tarmen Oct 15 '16

Hope this doesn't end up being too preachy or confusing:

Inheritance isn't a good way to do code reuse. If you want to be able to substitute all childs with the parent class in code inheritance is a great choice. Think car is a vehicle, inheritance models the is a part well.

In this specific case you might want to use an interface or move the method to the parent class. Obviously no hard and fast rules but once you work on somewhat larger code it is much easier to change or combine things when using interfaces instead of inheritance.

34

u/SlowerPhoton Oct 15 '16

Actually I have a lot of classes and each one of them would have exactly the same functions (apart from few new). Unfortunately interfaces won't help me.

66

u/remy_porter Oct 15 '16

Here from /r/bestof. Remember that interfaces can have default implementations of the methods, so you could just write an interface and use it as a mix-in to add functionality to classes. Depending on how complicated these methods are, that might be the best solution.

If it's more complicated, and these methods need to be really stateful, then this is still actually a really good case for doing collaboration instead of inheritance. Only use inheritance in cases of clear "is a" relationships. Always prefer collaboration over inheritance. What do I mean by collaboration?

Let's say, you've got a common batch of functions that we'll call DoXStuff. Let's declare an interface with a few methods to support that:

public interface DoesXStuff {
    void DoX1();
    void DoX2();
    boolean XisDone();
}

And then we'll make our class that implements that, which we'll call DoXStuff and we'll mark it as implements DoesXStuff. (skipping the implementation)

Now, you've got a bunch of classes that need to DoXStuff, so let's do this, let's give them each an instance of DoXStuff. Anytime they need to DoXStuff, they'll just delegate that responsibility to that private member- so they'll have a DoX1 method, but it actually just calls their private DoXStuff instances DoX1 method. In fact, we could even (ab)use default interface methods so that we can cut down on the repetitive code:

public interface DoXStuffDelegate extends DoXStuff {
    DoesXStuff getXDoer();
    default void DoX1() {
        this.getXDoer().DoX1();
    }
    default void DoX2() {
        this.getXDoer().DoX2();
    }
    default boolean XisDone() {
        return this.getXDoer().XisDone();
    }
}

So now, if I want to create a class that can have the important DoXStuff methods, I just have to do this:

public class ClassA implements DoXStuffDelegate {
    public DoesXStuff getXDoer() {
        return this.xdoer;
    }
    private DoesXStuff xdoer;
    public ClassA(DoesXStuff xdoer) {
        this.xdoer = xdoer;
    }
    //rest of ClassA's functionality goes here
}

This is marginally more code than just using inheritance, but the advantage here is that you're loosening up your coupling.

What I've sketched out here is a "sugary" version of the basic Delegate design pattern (that link has a more functional and less OO variation on the concept).

26

u/SlowerPhoton Oct 15 '16

Thanks for this great tip! I'll use it as soon as I have the option. However in my project there are many attributes (aside from functions designed to work with them). And those I can never put in an interface.

17

u/Mikegrann Oct 15 '16

Use an abstract class. It can have fields that are non-static and not final, can do all the implementation of "default" methods described (in fact, it was the only way to do it pre-Java 8), and won't require all this crazy wrapping of a delegate.

14

u/SlowerPhoton Oct 15 '16

But then I have to inherit anyways - from the abstract class. Isn't it true?

→ More replies (1)
→ More replies (4)
→ More replies (3)
→ More replies (10)

53

u/[deleted] Oct 15 '16

this guy is the real mvp... kinda encapsulates what this subreddit should be about :)

51

u/SerpentineLogic 💖 AUTZ 💖 Oct 15 '16

Always favour encapsulation

0

u/[deleted] Oct 15 '16

[deleted]

→ More replies (1)

115

u/SlowerPhoton Oct 14 '16

Imagine I have two instances of Child - if I change number to protected, will each instance have its own?

262

u/Rammite Shitty Support Main Oct 14 '16 edited Oct 15 '16

You need to look at the parent-child relationship differently.

For example, I might have a parent class "Vehicle".

public class Vehicle{
    public void startEngine()
}

All vehicles can start thier engines. This is a thing that is inherent to all vehicles.

public class Car extends Vehicle{
    public void driveOnRoad()
}

A Car is a Vehicle. Depending on how you are taught, this should stick out to you. A Car is-a Vehicle. Whenever you see "extends", it means the same thing as "is a", and vice versa. All Cars can drive on a road. However, they are also Vehicles, and so all Cars can start thier engines.

public class Plane extends Vehicle{
    public void flyInAir();
}

A Plane is-a Vehicle. Planes can fly in the air, and also start thier engines. Planes cannot drive on roads. Planes are not Cars, even though they have the same parent.


Privacy is important because programming is not a one-person job! You will have to work alongside other people, you will have to use someone else's work as reference, and if you play your cards right, someone will use your work as reference. Privacy makes sure that only people with permission can touch things.

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

private = Can be accessed by no one except itself. Good for secret things like myBankAccount and nukeLaunchCodes. Bad for global things like numberOfHumansInWorld and listOfEveryNode.

protected = Can be accessed by itself, and any children. Used for things like currentGasLevel - A vehicle needs to know this, but so does a Car and a Plane.

0

u/[deleted] Oct 15 '16

[deleted]

12

u/dave_a7x Oct 15 '16

Kim Jong Un hates you

→ More replies (1)

44

u/SerpentineLogic 💖 AUTZ 💖 Oct 15 '16

You forgot package level access, which is great for unit testing.

16

u/zshift Oct 15 '16

I find this confuses programmers that are just learning access levels for the first time. It's much easier to focus on the fundamentals, then introduce package and namespace concepts later.

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.

→ More replies (2)
→ More replies (2)

17

u/TheGuywithTehHat Oct 14 '16

Yes. All instances are independent, unless they have references to the same object. (But even in that case, the references are independent)

→ More replies (15)

13

u/submarine_golfcart Oct 15 '16

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

→ More replies (2)
→ More replies (10)