Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an interface part of the Object hierarchy?

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?

like image 943
ambar Avatar asked Dec 26 '22 14:12

ambar


1 Answers

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.

like image 106
Frank Avatar answered Dec 31 '22 15:12

Frank