inheritance

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
arjun gaur
Posts: 20
Joined: Sun Feb 16, 2014 3:28 am
Contact:

inheritance

Post 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..

arjun gaur
Posts: 20
Joined: Sun Feb 16, 2014 3:28 am
Contact:

Re: inheritance

Post by arjun gaur »

enthuware.ocajp.i.v7.2.1250

arjun gaur
Posts: 20
Joined: Sun Feb 16, 2014 3:28 am
Contact:

Re: inheritance

Post by arjun gaur »

sorry wrong qid.correct one is
enthuware.ocajp.i.v7.2.981

admin
Site Admin
Posts: 10398
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: inheritance

Post 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.

arjun gaur
Posts: 20
Joined: Sun Feb 16, 2014 3:28 am
Contact:

Re: inheritance

Post 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.

arjun gaur
Posts: 20
Joined: Sun Feb 16, 2014 3:28 am
Contact:

Re: inheritance

Post by arjun gaur »

oops i misread the question.B2 extends B and i thaught B2 extends B1.

Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests