Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion of super keyword in toString() method to super.toString() not happening

I have the following two classes as shown below. For the sake of simplicity, only toString overridden method is shown .

        public class Circle {
        @Override
            public String toString() {
                return "Circle";
            }
        }
        public class Cylinder extends Circle {
            @Override
            public String toString() {
     //     return "Cylinder"+this;  // runs without explicitly calling toString() on this keyword
     //     return "Cylinder"+super;  // throws error, asks to delete super token
            return "Cylinder["+super.toString(); // runs without error after adding .toString() with super keyword
            }

}

The issue i am having is in my understanding of super keyword . The toString() of super keyword should be invoked implicitly as is in the case of this keyword .In fact most of the tutorials and books refer to super keyword as a kind of an object reference to a super class and so it must behave same as this keyword when used with "+" concatenation operator inside toString(). Please help me in understanding this.

like image 602
Nishant_Singh Avatar asked Dec 18 '25 23:12

Nishant_Singh


1 Answers

The super keyword in Java is not an object reference, unlike this.

this is used as a reference to the calling object.

But, There's no reference-id which can be stored in super super is a keyword which is used to RESOLVE the parent CLASS, its methods and data members.

So, you can't print the value of super keyword. You can only access methods and members of parent class using super keyword.

this

super

Expressions

like image 190
Vaibhav Shitole Avatar answered Dec 20 '25 12:12

Vaibhav Shitole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!