Search code examples
javaarraysobjectarraylisttostring

How to pass toString from child to parent using super.toString() in Java


Working on a Java project to study Polymorphism. I am trying to learn how to pass a toString() up the line from the bottom child. I have to pass the toString form Hardware.java to Tool.java to ScrewDriver.java and then in Player.java, I need to print out an array that I have defined.

Here is the files:

public class Player {
    public static void main(String[] args) {
        List<Hardware> hardware = new ArrayList<>();
        ScrewDriver screwdriver1 = new ScrewDriver("Flathead", "Use this to open paint cans", 150, "Woodworking", true, 15, 10);

        hardware.add(screwdriver1);

        for(Hardware tool : hardware)
            System.out.print(tool);
    }
}

public class Hardware {
    private String name;
    private String message;
    private int points;

    @Override
    public String toString() {
        super.toString();
        return "Name: " + name + " Message: " + message + " Points: " + points;
    }
}

public class Tool extends Hardware {
    private String type;
    private boolean isDangerous;
    private int percentDangerous;

    @Override
    public String toString() {
        super.toString();
        return "Type: " + type + " Message: " + isDangerous + " Percent Dangerous: " + percentDangerous;
    }
}

public class ScrewDriver extends Tool {
    private double length;

    @Override
    public String toString() {
        super.toString();
        return "Length: " + length;
    }
}

The problem I am having is that the only thing that prints from the array is the Length.

Any help would be very much appreciated! Thank you in advance.


Solution

  • You cannot access a subclass's methods from a superclass. It is only possible the other way around. So you can access Hardware's toString() in Tool class and Tool's toString() in ScrewDriver class.

    In order to print toString() information of all the superclasses of ScrewDriver in ScrewDriver's toString() method, you need to modify all the toString() methods in this inheritance chain.

    Suppose that Hardware's toString() is like this:

    @Override
    public String toString()
    {
        return "Name: " + name + " Message: " + message + " Points: " + points;
    }
    

    You need to modify Tool's toString() to following, so that it uses its superclass's toString() method:

    @Override
    public String toString()
    {
        return super.toString() + " Type: " + type + " Message: " + isDangerous + " Percent Dangerous: " + percentDangerous;
    }
    

    And finally, ScrewDriver's toString() should invoke its superclass's toString() method as following:

    @Override
    public String toString()
    {    
        return super.toString() + " Length: " + length;
    }
    

    Only then ScrewDriver's toString() will print the information of all its superclasses.