Suppose that we have classes A, B, C and D. Suppose that B is a subclass of A, t
ID: 3581459 • Letter: S
Question
Suppose that we have classes A, B, C and D. Suppose that B is a subclass of A, that C is a subclass of B, and D is a subclass of A. Suppose that we make the following declarations.
A a1 = new A();
A a2 = new C();
D d1 = new D();
For each part below, explain what, if any, errors would be caused by the statement in that part. Be sure to consider both compile time and run time errors.
(a) A a3 = new B();
(b) B b1 = new A();
(c) B b2 = (B) a1;
(d) B b3 = (B) a2;
(e) B b4 = (B) d1;
(f) B b5 = (C)(A)new D();
Explanation / Answer
(a) A a3 = new B();
This is valid statement. We can create object for child class with parent class.
(b) B b1 = new A();
This will throw compilation error because we can not create parent class object with child class.
(c) B b2 = (B) a1;
This statement is syntactically correct. It will now throw any compilation error but it will throw run time exception. Because we can not explicitly cast parent class as child.
(d) B b3 = (B) a2;
This is valid statement because ultimately a2 is an instance of C which is inherited by B. We can explicitly cast sub class object into parent class.
(e) B b4 = (B) d1;
It will throw compilation error because there is no relation between B and D. So we can not convert D type object into B
(f) B b5 = (C)(A)new D();
This is syntactically correct but it will throw runtime exception because D type object can not be converted into A type object as they don't have relation.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.