Reputation: 653
So I was studying some OCAJP JAVA sample questions, and I stumbled on the following question.
Consider following code.
interface I{ }
class A implements I{ }
class B extends A { }
class C extends B{ }
And the following declarations:
A a = new A();
B b = new B();
which will compile and run without error?
A. a = (B)(I)b;
B. b = (B)(I) a;
C. a = (I) b;
D. I i = (C) a;
the answer to the problem was A. Which makes sense. What I don't understand though is that B. wasn't the correct answer. It said it was incorrect choice because "This will fail at run time because a does not point to an object of class B."
Now, I actually went to Eclipse and wrote down the entire code. C obviously didn't compile and D. failed at run time. B. compiled without issue at least with my code. Am I missing something here? or is the book actually wrong? The code that I actually put into Eclipse was this:
public class Test{
public static void main (String[]args){
A a = new A();
B b = new B();
a=(B)(I)b;
b=(B)(I)a;
}
}
interface I{ }
class A implements I{ }
class B extends A { }
class C extends B{ }
Upvotes: 3
Views: 493
Reputation: 9946
Problem here is sequential statements.
a=(B)(I)b;
b=(B)(I)a;
You have already assigned b
to a
in first statement. if you execute both statements independently (not in sequence) you will see the explained behavior.
Upvotes: 6
Reputation: 234
If you are prepairing for the OCP exam, you have to read the Study Guide of Jeanne Boyarsky and Scott Selikoff. To understand the inheritance relation between objects, you must ask the question: This ObjectA is a Object B?
Example: The Dog IS A Animal? Yeah, so Dog inherit from Animal. Remember that inheritance is a concept that have to represent consistence between business objects.
For casting, remember some rules:
Casting an object from a subclass to a superclass doesn’t require an explicit cast.
Casting an object from a superclass to a subclass requires an explicit cast.
Hope it helps.
Upvotes: 0