-5

Java code compiles but the toString method does not display. Do I need to call it in the subclass? or is there a different way for the toString to display the instance variables?

public class Animal { 
    //instance variables
    private int numberOfLegs; 
    private boolean sleep; 

    //Default Constructor
    public Animal() {
        numberOfLegs = 6;
        sleep = true;
    }

    // Constructor
    public Animal(int numberOfLegs, boolean sleep){
        this.numberOfLegs = numberOfLegs;
        this.sleep = sleep;
    }

    //toString method
    public String toString (int numberOfLegs, boolean sleep){
        return numberOfLegs + " legs, sleep: " + sleep;
    }
    //walk method
    void walk(){
        System.out.print("walking ");
    }
    public static void main(String[] args) {
        Animal animal1 = new Tiger();
        animal1.walk();
        animal1.toString(4, false);
    } //end main
}// end animalclass

class Tiger extends Animal {
    void walk(){
        super.walk();
        System.out.println("a Tiger");
    }
    public Tiger(){
        super();
    }
} //end Tiger class
C.Champagne
  • 5,381
  • 2
  • 23
  • 35
silverFox
  • 1
  • 1

1 Answers1

0

toString() returns a String. It does not perform any display logic (unlike your walk() method which prints things and returns nothing).

You need to display it with System.out.println() or other means.

The toString() method also shouldn't be taking arguments. You already know how many legs the animal has, so the parameters are useless.

Kayaman
  • 72,141
  • 5
  • 83
  • 121