0

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;
    }
}
1
  • 1
    classic case of inheritance. Create subclasses, use versions of super Commented May 4, 2022 at 13:26

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Create a second constructor that sets these values

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.