Joseph Loomis
Joseph Loomis

Reputation: 9

Getter method not returning value set in object constructor

I ' taking the Amazon Junior Dev Course on Coursera and working my way through the final project of the first course, which focuses on inheritance and polymorphism.

The broader assignment is to create a zoo. The structure of the problem I am working on currently is that there is an abstract class at the top, Animal, and two child classes, Tiger and Dolphin.

The assignment is for me to build the subclasses while calling the default constructor of the parent class such that I could pass a specific string through the constructor in the main method when instantiating the Tiger and Dolphin objects and have the getter method inherited from the abstract parent class return that string as nameOfAnimal, or the string property instantiated in the parent class and inherited through the child classes via the constructor.

In the parent class, Animal:

String nameOfAnimal;

// no argument constructor
public Animal() {
      nameOfAnimal = "Unknown Animal";
    }

    // parametrized constructor
public Animal(String nameOfAnimal) {
       this.nameOfAnimal = nameOfAnimal;
    }

public String getNameOfAnimal() {
        return nameOfAnimal;
    }

    public void setNameOfAnimal(String nameOfAnimal) {
        this.nameOfAnimal = nameOfAnimal;
    }

In the sub classes, calling the super class' constructor:

 public Tiger(String nameOfAnimal){
        super();

Given the code above in the parent and child classes, I have tried the following in the main method:

Tiger tigerObject = new Tiger("Tiger");

The task is to use a getter method to return the name of the animal, such that System.out.println("The animal which is chosen is : " + tigerObject.getNameOfAnimal()); would return The animal which is chosen is: Tiger

Unfortunately, no matter what configurations I try, it returns The animal which is chosen is: Unknown Animal, which I recognize to be what would be returned if I were to have called the no argument constructor rather than the parametrized constructor.

Since I instantiated the object, specifically passing "Tiger" as nameOfAnimal, I cannot for the life of me figure out what I am doing wrong.

Upvotes: 0

Views: 92

Answers (1)

Mario Mateaș
Mario Mateaș

Reputation: 1216

Your Tiger constructor should delegate the nameOfAnimal parameter to the superclass like this:

public Tiger(String nameOfAnimal){
        super(nameOfAnimal);
}

By adding a parameter to the super() from the above example, you are calling Animal's constructor with the parameter offered in the subclass, thus it will be set as a field.

If you only call super(), you are actually delegating the action to the first, non-args constructor, that will initialize your animal's name as Unknown Animal.

Upvotes: 4

Related Questions