What is the output of the following program?
interface InterfaceDemo {
public int size=40;
void m1();
}
class T implements InterfaceDemo {
public int size=10;
public void m1() {
System.out.println("T:m1()" + size);
}
}
class SubT extends T implements InterfaceDemo {
public int size=20;
public void m1() {
System.out.println("SubT:m1()" + size);
}
}
class Param
K k;
public void m1() {
System.out.println("Param T:m1()" + size);
System.out.println("K:" + K.size);
}
}
public class RawTypeParameterizedTypeExamples {
public static void main(String[] args) {
Param param=new Param();
System.out.println(Param.size);
param.m1();
param.k=new SubT();
System.out.println("param.t.size:" + param.k.size);
param.k.m1();
Param
param1=param;
System.out.println(param1.k.size);
param1.k.m1();
}
}
Output:
It prints:
40
Param T:m1()40
K:40
param.t.size:40
SubT:m1()20
10
SubT:m1()20
Reason:
Variables of a raw type can be assigned from values of any of the type's parametric instances.
For instance, it is possible to assign a Vector
The reverse assignment from Vector to Vector
(since the raw vector might have had a different element type),
but is still permitted using unchecked conversion in order to enable interfacing with legacy code.
In this case, a compiler will issue an unchecked warning.
Hence this line param.k=new SubT(); and param1=param; gives us unchecked warning as we are trying to do reverse assignment.
40 Param T:m1()40 are printed as the values are inherited from interface.
param.k.size gives 40 only as Type variable is not set at this point of time and hence retrieves values frm interface.
param1.k.size prints 10 as it retrieves value from Type Variable T only but not from SubT as variables donot get overrided.
param1.k.m1() finally prints "SubT:m1()20" as we have assigned param object to param1.
Hope this explanation helps and please suggest if any.
No comments:
Post a Comment