Search code examples
javainheritancepolymorphismtostring

Problem with printing - Inheritance, Polymorphism and toString


I am practicing how to use toString(), polymorphism and inheritance. Right now I have the code below and it has all the information that I want to print and it does print but I have some unwanted lines.

enter image description here

I just need the 1st and 3rd line but I'm not so sure why it's printing out the other 3 lines.

public class Test_toString{
    public static void main(String[] args){
        Car c = new Car();
        System.out.println(c.toString());

        NamedCar c2 = new NamedCar(160, 8, "green", "Pony");
        System.out.println(c2.toString());
    }
}

class Car{
    int speed;
    int gear;
    public String color;

    public Car(){
        speed = 100;
        gear = 5;
        color = "silver";
    }

    public Car(int speed, int gear, String color){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
    }

    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + "\n" + super.toString();
    }
}

class NamedCar extends Car{
    public String name;

    public NamedCar(String name){
        super();
        this.name = name;
    }

    public NamedCar(int speed, int gear, String color, String name){
        this.speed = speed;
        this.gear = gear;
        this.color = color;
        this.name = name;
    }


    public String toString(){
        return "Car: " + speed + "km/h " + gear + " gears " +
        color + " " +  name + "\n" + super.toString(); 
    }
}

Solution

  • Just remove method call super.toString() from toString() method in both classes. When you make that call you are calling toString() method from parent class. So when it is called from NamedCar class, it calls toString() method from Car class and when it is called from Car class it calls toString() from object class.