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.
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.
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.
Constructors are called only once at the time of the creation of the object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With