Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do interfaces have toString method? [duplicate]

Tags:

java

interface

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);
    }
}
like image 301
Akhilesh Dhar Dubey Avatar asked Aug 25 '12 17:08

Akhilesh Dhar Dubey


People also ask

Is it possible to extend an interface with ToString method?

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? .

What is the use of toString 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.

What happens when you override the toString () method in Java?

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.

Which interface has all the methods of an object?

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.


1 Answers

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 Object is the root of the class hierarchy. Every class has Object as 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.

like image 187
mre Avatar answered Oct 08 '22 21:10

mre