How can I use the method of accessing the interface of the Object class?

interface Intf {
}

class A implements Intf {
}

class Test {    
    public static void main(String[] args) {
        Intf obj = new A();
        obj.toString();
    }
}

A friend showed me this code, I could not explain it to him ...

We know that methods defined in a "specified" object can only be executed on an instance. As we can see, no method is defined Intf, but obj (which refers to Intf) is able to call the method toString()of the Object.class object

I consoled him by saying that this is all an object in Java (although we do not get the autocomplete option in the eclipse IDE against Intf)

+5
source share
7 answers

As we can see, no method is defined Intf

Actually, Intfthere is an implicitly declared toStringmethod.

( ) Object.

Java, § 9.2 .

9.2

[...]

  • , , - m s, r th, m s, r throws, Object, , throws .

[...]

+10

, , .

- , , , , . Intf , .

,

class A {}

, obj.toString() , , java.lang.Object ?

, , , . , Object , , , .

+2

Java Object, , , toString().

+1

, . , , - / ( , ).

Java java.lang.Object, , toString(). , .

: http://download.oracle.com/javase/6/docs/api/java/lang/Object.html

+1

Object, Object. :

, .

.

, -, .

, m , m Object.

, -, public instance. : http://ohmjavaclasses.blogspot.com/2011/11/is-intreface-inherits-object-clashow.html

+1

What's the question? The last sentence is the answer: everything extends Object in Java

0
source

Chceck it too. I asked the same question a while ago

Interfaces inherit from class Object in java

0
source

All Articles