Page 1 of 1

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Mon Feb 24, 2014 4:02 am
by arjun gaur
Answer is wrong..look at this code.there should be an Is-a relationship,and since the access is "default" so both classes should be in same package.
class A
{
int a;
}
class B extends A
{
public static void main(String[] args)
{
B b=new B();
A a=new A();

System.out.println(b.a);
}
}

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Mon Feb 24, 2014 4:29 am
by admin
I have no idea what you mean. Can you explain why you think the given answer is wrong?

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Sun Oct 26, 2014 3:11 pm
by Tony.Singarayar

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
  }
}
i think b1 = (B1) b; has the logic as b2 = (B2) b1


Why is b1 = (B1)b; correct over b2 = (B2)b1? can you please explain?

Thanks,
Tony Singarayar

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Sun Oct 26, 2014 7:24 pm
by admin
No, it doesn't have the same logic. It is possible for b to point to an object of clasd b1 but it is not possible for b1 to point to an object of class b2 at all.

Think of it this way - an animal reference can point to a Dog or a Cat, but a dog reference can never point to a Cat because a Dog is an Animal but a Cat can never be a Dog.

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Sat Jan 24, 2015 7:04 pm
by padraig
Hi, can you post a link to where this casting is explained?
Thanks

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Sat Jan 24, 2015 8:11 pm
by admin
This is quite fundamental. Any good Java book will do. Or just google.

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Sun Jan 10, 2016 5:41 am
by liviu_varlam
why are there 2 casts required for the last line?

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Sun Jan 10, 2016 9:03 am
by admin
Two casts are not needed. Actually, no cast is needed here. The explanation is only trying to illustrate that after casting b1 to B, you have to cast it again to B1 to make it work.
The explanation has now been updated to make it clear.
thank you for your feedback!
Paul.

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Wed Jan 27, 2016 11:01 am
by dmcler
first answer is right, but wrong answer is highlighted green

Re: About Question enthuware.ocajp.i.v7.2.1250 :

Posted: Wed Jan 27, 2016 11:37 am
by admin
The question is asking which lines will fail. That is why option 3 is highlighted in green. It is the right option.