George Newton
George Newton

Reputation: 3303

Avoiding duplicate code in constructors

I have Java code that looks something like this:

public class Animal {
    Animal(String name) {
    // some code
    }
}

And a subclass like this:

public class Dog extends Animal {
    Dog(String name) {
    // SAME code as Animal constructor
    }
}

The only difference between Dog and the Animal is that Dog has some methods that override the superclass. Their constructors have exactly the same code. How can I avoid this duplicated code? I know that an object can't inherit constructors.

Upvotes: 0

Views: 1275

Answers (2)

arshajii
arshajii

Reputation: 129572

You can delegate to the super constructor:

Dog(String name) {
    super(name);
}

See also: http://docs.oracle.com/javase/tutorial/java/IandI/super.html.

Upvotes: 3

David
David

Reputation: 1970

If the constructors are the same you don't need to it in Dog. You have access to the Animal constructor from Dog by calling super(name);.

public class Animal {
    Animal(String name) {
    // some code
    }
}

And in Dog:

public class Dog {
    Dog(String name) {
        super(name);
    }
}

It's worth noting that a call to a superclass' constructor must be the first line in your constructor. But after you have called super(name) you can go on and do other Dog-specific code.

For example:

public class Dog {
    Dog(String name) {
        // You can't put any code here
        super(name);
        // But you can put other code here
    }
}

Upvotes: 6

Related Questions