Is the interface part of the hierarchy of objects?

Please find the code snippet below which the question is explained.

public class Test { /** * @param args */ public static void main(String[] args) { I ref = new B(); ref.equals(""); } } interface I{ } class A { public void method(){ } } class B extends A implements I{ } 

Refer to main() , ref.equals() allowed, but ref.method() not allowed. Why is that?

EDIT: An object is a superclass of B (or A or any other class), but in the same way A is also a superclass of B. My question is why A 'method ()' does not appear in 'ref', i.e. why is ref.equals () allowed but ref.method () not? How is the visibility check of this method performed? Is it related to the JVM?

+4
source share
6 answers

This is because you declared it as I:

 I ref = new B(); 

You will see only the methods declared in i and the methods from Object .

when you do:

Declare it as A:

 A ref = new B(); 

or declare it as B

 B ref = new B(); 

or pass it A

 I ref = new B(); ((A)ref).method() 

You will have access to:

 ref.method() 

and to be complete, if you like to see the methods from A and I, you can impose an object on them. Or I have an implementation of I.

+7
source

The Java language specification states that java.lang.Object is a direct supertype of all interfaces that do not have any superinterfaces.

+2
source

When you reference an object using its interface, for example

  I ref = new B(); 

then you have access only to the interface and methods of the object class . You do not have the class methods visible until you add the object to your class.

If you want to access the method declared in class A , you can do one of the following:

  I ref = new B(); ((A)ref).method() 

or

  A ref = new B(); ref.method(); 

or

  B ref = new B(); ref.method(); 
+1
source

An interface type can only be created using a specific class, which by default is a subclass of Object. Therefore, you can call methods in Object by the type of interface. All other user methods can be called by interface type only if they are declared in this interface or its super interfaces.

0
source

If you reference an object through an interface, you can only access the methods that the interface provides.

0
source

ref.equals() allowed because equals() is a method from an object and is accessible to all subclasses (even B, because B implicitly extends Object ).

If method () is not in B, you cannot access it when your operator I i = new B() .

0
source

Source: https://habr.com/ru/post/1445436/


All Articles