Reputation: 883
class A is abstract and class B extends class A now class A reference can hold object of class B,that is
A aObj = new B();
and assume class B has some extra methods.... like
class A
{
public show();
}
class B extends A
{
public show(){}
public method1(){}
private method2(){}
}
now tell me what things variable aObj can access from class B can it access everything?
Upvotes: 1
Views: 1165
Reputation: 23950
aObj can only use show() as the compiler thinks aObj is of type A, and the only known method of A is show().
If you know that you actually have a B you can cast that object to a B:
if (aObj instanceof B.class) {
B bObj = (B) aObj;
bObj.method1(); //OK
} else {
log.debug("This is an A, but not a B");
}
aObj.show();
Upvotes: 2
Reputation: 5589
For reference and completeness, here's a list of the possibilities:
A aObj = new B();
aObj.show(); // Works
aObj.method1(); // Error
aObj.method2(); // Error
And with casting to B:
B bObj = (B)aObj; bObj
bObj.show(); // Works
bObj.method1(); // Works
bObj.method2(); // Works inside bObj, but error otherwise
Upvotes: 3
Reputation: 185842
aObj only sees the public show()
method. If you cast aObj to B, you can then access public method1()
. public method2()
is only accessible to the implementation of B.
Upvotes: 3