interface MyInterface { // Methods of MyInterface } public SomeClassimplements M
ID: 3657431 • Letter: I
Question
interface MyInterface
{
// Methods of MyInterface
}
public SomeClassimplements MyInterface
{
// All methods of SomeClass and MyInterface
}
SomeClass obj = new SomeClass( );
a.MyInterface miobj = obj;
b.SomeClass obj2 = miobj;
c.miobj.aMethodOfSomeClass( );
A.Is statementaabove legal, or is casting required? Explain.
B.Statementbis trying to assign the SomeClass object refered to by miobj to a SomeClass reference variable obj2. What is wrong with this statement and how would you fix it.
C.In statementc, an interface reference is trying to access a SomeClass class method that is not part of MyInterface. Is this legal? Explain.
Explanation / Answer
A. Statement A is legal as casting is required when a reference of a class or an interface on a lower level of heirarchy refers to an interface or a class which it extends. but in this case a reference of the type MyInterface is referring to the object of SomeClass type. Hence it is legal and casting is not required. B. As according to above logic, an object reference of type SomeClass cannot refer to an object of type MyInterface hence in this case casting is required. i.e. SomeClass obj2= (SomeClass) miobj; C. This is not legal. An object of an interface or a parent class can access only those methods of the subclass which are overidden in the class which inherits the above interface/class.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.