5

I have the following code;

abstract class Animal{

    public String name;
    public int legCount;

    //If has no leg count
    public Animal(String name){
        this.name = name;
        this.legCount = 4;  //Default leg count is 4

        System.out.println("Created animal: " + name);
    }

    //If has a leg count
    public Animal(String name, int legCount){
        this.name = name;
        this.legCount = legCount;

        System.out.println("Created animal: " + name);
    }}

I have repeated System.out.println("Created animal: " + name); twice. Is there a way to remove this repeated code, so it only runs once? having multiple constructors can make this a bit of a pain.

daedsidog
  • 1,732
  • 2
  • 17
  • 36
Lewy Willy
  • 81
  • 1
  • 4
  • 3
    1 constructor can call the other. Each overloaded constructor should just set a particular value and then call the next constructor in the chain until you get to the main one that sets all the variables. – takendarkk Dec 17 '18 at 22:32

3 Answers3

10
class Animal{

    public String name;
    public int legCount;


    public Animal(String name){
        this(name,4);
    }

    public Animal(String name, int legCount){
        this.name = name;
        this.legCount = legCount;
        System.out.println("Created animal: " + name);
    }


}

now you only repeat the printing line once

the 1 parameter constructor call the 2 parameters constructor with the default value 4.

Naor Tedgi
  • 5,204
  • 3
  • 21
  • 48
5

In your constructor that only takes a name, have it delegate to the other constructor by calling:

public Animal(String name){
    this(name, 4);
}

This will delegate to the other constructor so that none of the code is repeated. This will not only have only one line of code that calls System.out.println, it will also have only one line of code that assigns to name and only one line of code that assigns to legCount.

rgettman
  • 176,041
  • 30
  • 275
  • 357
-1

The question has already been answered:

Simply link all your constructors to one single constructor that would eventually execute your command. One thing that is worthy of note, however, is to make sure none of the constructors have the same signature. This is very important! If one constructor takes in two String parameters, there should be no other constructor that accepts two Strings. Java forbids multiple constructors with the same parameters.

I hope this helps.. Merry coding!

Taslim Oseni
  • 6,086
  • 10
  • 44
  • 69