How is it possible to call toString method using the reference variable of interface Test, which does not have a toString method?
interface Test
{
void show();
String toHi();
}
class Demo implements Test
{
public void show(){
System.out.println("Show");
}
public String toString(){
return "Hello";
}
public String toHi(){
return "Hi";
}
public static void main(String[] args)
{
Test t=new Demo();
String s=t.toString();
System.out.println(s);
}
}
And the toString method is one of them. But, note that interfaces don't implicitly extend any super interface (or class) unlike classes which implicitly extend the Object class. You will find a better explanation here - Do Interfaces really inherit the Object class in Java? .
Java toString () method If you want to represent any object as a string, toString () method comes into existence. The toString () method returns the string representation of the object. If you print any object, java compiler internally invokes the toString () method on the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Show activity on this post. Object has a toString () method, so everything (except primitive types) has a toString () method. Java will treat anything, even an empty interface, as having all the methods of Object, because it always does. Show activity on this post. Any Object has a toString () method.
Since class Demo implicitly extends class Object, it inherits method toString. And since that's not an abstract method, class Demo is not forced to provide an implementation, although you're able to directly invoke toString on an instance of Demo. For more information, please see Lesson: Interfaces and Inheritance.
As stated in the Object API,
Class
Objectis the root of the class hierarchy. Every class hasObjectas a superclass. All objects, including arrays, implement the methods of this class.
Also, note that the toString method is not part of the interface definition, but rather the Object class definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With