0

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.

2 Answers 2

6

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 } } 
Sign up to request clarification or add additional context in comments.

Comments

3

You can delegate to the super constructor:

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

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

5 Comments

Haha. I was just about to post exactly this, but SO prevented me because you were faster. ;)
Won't that make my Dog object an Animal object?
@SotiriosDelimanolis is right. Your Dog object is an Animal object, regardless of whether you call the super constructor. For example, if you have class Dog, class Cat, and class Fish, which all extend class Animal, they can all be put into the same Animal array.
Note that it's impossible to NOT call the superclass constructor. If you don't call another constructor explicitly, the compiler will insert an implicit call to the no-argument super constructor at the top of your constructor.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.