Home > other >  Java constructor with default values
Java constructor with default values

Time:05-04

thx for reading.

I need to create constructor, which in one case has default values example below. this code is wrong of course, Is it possible to do that it means in case "dog" constructor will not ask for parameters: weight, age and will fill up class fields: weight=1, age=1. In another case for example cat will ask for all parameters? How usually this problem is solved?

public Animal(String spacies, String name, double weight, byte age, boolean isALive){

    if (spacies.equals("dog")) {

        this.name = name;
        this.weight= 1;
        this.age = 1;
        this.isALive = isALive;

    } else {
        this.spacies = spacies;
        this.name = name;
        this.weight = weight;
        this.age = age;
        this.isALive = isALive;
    }
}

CodePudding user response:

Best way is to use inheritance. Animal is abstract entity. You should derive specific animals from those. There can be different approaches. Tried to provide one simple solution.

    public abstract class Animal {


    private final String species;
    private final String name;
    private final double weight;
    private final byte age;
    private final boolean isALive;

    public Animal(String species, String name, double weight, byte age, boolean isAlive) {
        this.species = species;
        this.name = name;
        this.weight = weight;
        this.age = age;
        this.isALive = isAlive;
    }

}

class Dog extends Animal {
    public Dog(String dogName, boolean isAlive) {
        super("Dog", dogName, 1.0, (byte) 1,isAlive);
    }
}

Try relating to real world when working on OOPS concepts. Hope this helps.

CodePudding user response:

Create a second constructor that sets these values

public Animal(String spacies, String name, boolean isALive){
    this("dog", name, 1, 1, true)
}
  • Related