简体   繁体   中英

toString,hashcode and equals method inside interface

Below example runs without any errors, can any one explain me how this works?, as interface doesn't contain any toString()/hashcode/equals method declaration how compiler will resolve method call?,as per my understanding toString()/hashcode/equals or Object class methods will be declared by default inside interface? please correct me if am wrong

interface int1 { public void show(); }

class inttest implements int1
{

    public void show() 
    {
        System.out.println("inttest.show()");
    }

    @Override
    public String toString()
    {
        return "tostring called";
    }
}

public class MainClass1
{
    public static void main(String[] args) {
        int1 i=new inttest();
        System.out.println(i.toString());

    }
}

Any interface has all the public methods of the Object class (it either inherits them from a super-interface or declares them implicitly if it doesn't already declare them explicitly).

This makes sense, since any implementing class of any interface must be a (direct or in-direct) sub-class of the Object class, and therefore will inherit an implementation of all the Object methods.

9.2. Interface Members

If an interface has no direct superinterfaces, then the interface implicitly declares a public abstract member method m with signature s, return type r, and throws clause t corresponding to each public instance method m with signature s, return type r, and throws clause t declared in Object, unless an abstract method with the same signature, same return type, and a compatible throws clause is explicitly declared by the interface.

随着所有对象的扩展, ObjectObject具有toString()您正在调用该方法。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM