Given:
public class SampleClass {
public static void main(String[] args) {
AnotherSampleClass asc = new AnotherSampleClass();
SampleClass sc = new SampleClass();
// TODO code application logic here
}
}
class AnotherSampleClass extends SampleClass {
}
Which statement, when inserted into line “// TODO code application logic here”, is valid change?
A.
asc = sc;
B.
sc = asc;
C.
asc = (object) sc;
D.
asc = sc.clone ()
Explanation:
Works fine.
Incorrect answers:
asc = sc.clone();
Incompatible types.
asc =sc;
Incompatible types.
asc = (object) sc;
Syntax error
B
Why??
asc is-a sc.
With inheritance, you can also refer to an object of a derived class using a variable
of a base class or interface.
The Answer is B. SampleClass (base class) cannot be converted or cast to AnotherSampleClass (derived class). Remember the order:
baseClassReference = derivedClassReference;
is allowed, but not vice versa:
derivedClassReference = baseClassReference; // won’t compile