Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove repeated code in constructors? [duplicate]

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.

like image 518
Lewy Willy Avatar asked Dec 17 '18 22:12

Lewy Willy


People also ask

Can you override constructors?

It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.

What is constructor overriding overloading?

The constructor overloading can be defined as the concept of having more than one constructor with different parameters so that every constructor can perform a different task. Consider the following Java program, in which we have used different constructors in the class.

Can a class constructor be called more than once?

Constructors are called only once at the time of the creation of the object.


1 Answers

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.

like image 98
Naor Tedgi Avatar answered Oct 21 '22 18:10

Naor Tedgi