Page 1 of 1

inheritance

Posted: Mon Feb 24, 2014 3:50 am
by arjun gaur
Q-82 of 91 QId

Code: Select all

class B {}
class B1 extends B {}
class B2 extends B {}
public class ExtendsTest{
  public static void main(String args[]){
     B b = new B();
     B1 b1 = new B1();
     B2 b2 = new B2();
     // insert statement here
  }
}
If b2 = (B2)b1 won't compile as b1 can never refer to an object of class B2 then how can b1=(B1) b compile ??but it says that it will fail at runtime..although in both cases we are assigning a reference variable of base class to a reference variable of it's derived class.
Please explain..

Re: inheritance

Posted: Mon Feb 24, 2014 3:51 am
by arjun gaur
enthuware.ocajp.i.v7.2.1250

Re: inheritance

Posted: Mon Feb 24, 2014 3:52 am
by arjun gaur
sorry wrong qid.correct one is
enthuware.ocajp.i.v7.2.981

Re: inheritance

Posted: Mon Feb 24, 2014 4:32 am
by admin
Did you try it out?
It is possible for a base class reference to point to a subclass object. So compiler knows that b can point to an object of class B1, therefore b1 = (B1) b; is valid at compile time.

Re: inheritance

Posted: Wed Feb 26, 2014 8:42 am
by arjun gaur
i didn't tried but this is what i said that a base class reference can point to an object of derived class.we can apply the same to b2=(B2)b1.b1 is the base class so it can point to an object of derived class B2.

Re: inheritance

Posted: Wed Feb 26, 2014 8:59 am
by arjun gaur
oops i misread the question.B2 extends B and i thaught B2 extends B1.