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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With