1Z0-808 · Question #87
Given: 1. public class SampleClass { 2. public static void main (String[] args) { 3. AnotherSampleClass asc = new AnotherSampleClass(); 4. SampleClass sc = new SampleClass(); 5. //Insert code here…
The correct answer is B. sc = asc. Option B works because AnotherSampleClass is a subclass of SampleClass, meaning every AnotherSampleClass object is a SampleClass. Assigning a child-type reference (asc) to a parent-type variable (sc) is called upcasting (widening), which Java performs implicitly and safely…
Question
- public class SampleClass {
- public static void main (String[] args) {
- AnotherSampleClass asc = new AnotherSampleClass();
- SampleClass sc = new SampleClass();
- //Insert code here
- }
- }
- class AnotherSampleClass extends SampleClass {
- }
Options
- Aasc = sc;
- Bsc = asc;
- Casc = (Object) sc;
- Dasc = sc.clone;
How the community answered
(38 responses)- A5% (2)
- B89% (34)
- C3% (1)
- D3% (1)
Explanation
Option B works because AnotherSampleClass is a subclass of SampleClass, meaning every AnotherSampleClass object is a SampleClass. Assigning a child-type reference (asc) to a parent-type variable (sc) is called upcasting (widening), which Java performs implicitly and safely without any cast syntax.
Why the others fail:
- A (
asc = sc) attempts a downcast without an explicit cast operator. The compiler can't guarantee that theSampleClassreference actually points to anAnotherSampleClassobject, so it refuses to compile. - C (
asc = (Object) sc) castsscup toObject, making the type even more general. Assigning anObjectto anAnotherSampleClassvariable is an even wider downcast and won't compile without an explicit(AnotherSampleClass)cast. - D (
asc = sc.clone) is syntactically invalid -cloneis a method and must be called with parentheses (clone()). Even then,clone()returnsObject, which still couldn't be assigned toascwithout casting.
Memory tip: Think of it as a job posting - a parent class is the job title and a child class is a specific employee. You can always say "this employee fills the role" (child → parent), but you can't say "this job title is specifically this one employee" (parent → child) without a verified check (explicit cast).
Topics
Community Discussion
No community discussion yet for this question.