4

Please find the code snippet below which explains the question.

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{

}

Please refer to main(), ref.equals() is allowed but ref.method() is not allowed. Why is so?

EDIT: Object is the super class of B (or of A or of any other class) but in the same way A is also a super class of B. My question is why A's 'method()' is not visible in 'ref', i.e. why ref.equals() is allowed but ref.method() isn't? How this method visibility check is done? Is it rooted the JVM?

Frank
  • 16,476
  • 7
  • 38
  • 51
ambar
  • 2,053
  • 6
  • 27
  • 32

6 Answers6

7

That is because you did declare it as an I:

I ref = new B();

You will only see 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 Cast it to 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 cast you object between them. Or have A implement I too.

Frank
  • 16,476
  • 7
  • 38
  • 51
2

Java Language Specification states that java.lang.Object is a direct supertype of all interfaces that do not have any superinterfaces.

msell
  • 2,168
  • 13
  • 30
1

When you refer an object using its interface e.g.

       I ref = new B();

then you have accessibility of the interface and Object class methods only. You don't have any visibility of class methods until you cast the object to its class.

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

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

or

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

or

    B ref = new B();
    ref.method();
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
0

An interface type can be instantiated only using a concrete class which is by default a sub class of Object. Hence you can call the methods in Object on an interface type. All other custom methods can be called on an interface type only if they are declared in that interface or its super interfaces.

Vikdor
  • 23,934
  • 10
  • 61
  • 84
0

If you refer an object through interface then you can only access the methods which the interface exposes.

GuruKulki
  • 25,776
  • 50
  • 140
  • 201
0

ref.equals() is allowed because equals() is method from object and available for all subclasses (even B because B implicitly extends Object).

if method() is not in B, you can't access it when your statement is I i = new B().

kosa
  • 65,990
  • 13
  • 130
  • 167