user489041
user489041

Reputation: 28312

Java Inheritance Question

Say I extend a class and override a method in this class. Why is it bad practice to then call the overridden method from the constructor of my new class?

Upvotes: 3

Views: 1359

Answers (5)

Feanor
Feanor

Reputation: 2725

Because the resulting instance of the class could be in an inconsistent state. Here's a concrete example.

public class Foo {
    private int number;

    public Foo() {
        number = 42;
        multiplyNumber();
    }

    public void multiplyNumber() {
        number = number * 2;
    }

    public int getNumber() {
        return number;
    }
}

public class Bar extends Foo {

    private int number;

    public Bar() {
        multiplyNumber();
    }

    @Override
    public void multiplyNumber() {
        number = number * 3;
    }
}

public class FooBar {

    public static void main(String[] args) {
        Foo foo = new Foo();
        Foo bar = new Bar();
        System.out.println("Foo number 1 = " + foo.getNumber()); // Returns 84
        System.out.println("Foo number 2 = " + bar.getNumber()); // Returns 42; 
    }
}

When running through a debug on my machine, bar never actually calls the multiplyNumber() method in the constructor; it just gets skipped. As a result, the object doesn't have the expected value in number.

Constructors should be simple creatures; best not to put anything very complicated in there.

Upvotes: 3

nsfyn55
nsfyn55

Reputation: 15363

Imagine that you call an overridable method in your constructor. you subclass again and override again. The second subclass can interrupt the work that your first subclass depends on to be deemed fully intialized thus leaving it in a corrupted state.

As for work in the constructor. You can do work, it just generally should be the type of work that is required to initialize your object.

For a best practice, avoid inheritance all together and if you decide to divide constructor work up into methods use visibility modifiers to ensure that all that work remains local to the class being constructed.

Upvotes: 1

Rob Harrop
Rob Harrop

Reputation: 3473

The main reason not to call overridable methods from constructors is that it allows subclasses to see the class in a half-constructed state. This may or may not be security risk, but it's a bug waiting to happen. Read more here.

Upvotes: 12

sclarson
sclarson

Reputation: 4422

Someone can inherit from your class and change the behavior that you are relying upon in your constructor.

This means that you do not know what you that function is going to do.

Upvotes: 3

Bozho
Bozho

Reputation: 597402

It is generally a bad practice to do work in the constructor - just get and assign the object dependencies.

Upvotes: 5

Related Questions