Question

I have a question about calling toString method, wich i have declared in parent class, on extended objects saved in arrayList. I have parent "Product" class, then i have extended class "Smartphone".

My problem is that I have declared toString() method in parent class and in extended class and I need to call both methods, but i don't know how to call parent toString() method on extended objects stored in arrayList. Thank you for advice.

Was it helpful?

Solution

You need to use super to reference your parent class.

class A {
    @Override
    public String toString() {
        return "A's toString()";
    }
}

class B extends A {
    @Override
    public String toString() {
        return super.toString() + " " + "B's toString()";
    }
}

B b = new B();
System.out.println(b); // prints "A's toString() B's toString()"

Edit:

If your child's toString() always calls the parent's, then you don't even need the toString() in the child.

If you want to keep a custom toString() for your child that is different than the parent's in some case, but you also want to be able to call the parent's toString() from the child, make a delegation method.

class B extends A {
    @Override
    public String toString() {
        ...
    }

    public String parentsToString() {
        return super.toString();
    }
}

B b = new B();
b.parentsToString(); // will return the output of A's toString()

OTHER TIPS

by default each object reference we write ,it internally calls its own toString method.

if its not defined then it will call its immediate parent's toString() method.

but if you want to call parent's toString() method using child reference variable then

define toString in child and call parent's toString and append its own definition.

example

class Parent {
    @Override
    public String toString() {
        return "Parent";
    }
}

class Child {
    @Override
    public String toString() {
        return super.toString() + " " + "child";
    }
}

Child child = new Child();
System.out.println(child); // prints parent child
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top