tags:

views:

76

answers:

3

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?

+1  A: 

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();
extraneon
that means...it cant access method1() and method2()?
shraddha
@shradda, the `show()` method called via an A reference is implemented in B and as such it (`B::show()`) can call `method1()` and `method2()` although they are not visible through the A reference.
rsp
+3  A: 

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.

Marcelo Cantos
+3  A: 

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
Colin Gislason