Given the code fragment:
public class Employee {
String name;
transient String companyName;
}
public class Manager extends Employee implements Serializable {
String mgrId;
public static void main(String s[]) throws Exception {
Manager mgr = new Manager();
What is the result?
A.
M001, ,
B.
M001, null, null
C.
M001, Sam,
D.
M001, Sam, null
E.
M001, Sam, ABC Inc
F.
Compilation fails
G.
A NullPointerException is thrown at runtime
this is a strange question, can anybody explain?
E why? I don’t know š
Looks like an incomplete question…
I think same
It is missing something in the question, but you can answer D
Because it will serialize
Field mgrId in the class Manager,
Field name because of the inheritance (class Manager extends Employee).
And the field companyName is transient, so it won’t be serialized.
So, for me it’s D ! Because serialize a transient field will take the default value. Null for String.
Manager mgr = new Manager();
mgr.mgrId = “M001”;
mgr.name = “Jim”;
mgr.companyName = “XYZ Inc”;
// assume correct serialisation of mgr
// assume correct deserialization of mgr
System.out.println(mgr.mgrId+”,”+mgr.name+”,”+mgr.companyName);
public class Employee {
String name;
transient String companyName;
public Employee(){
name = “Sam”;
companyName = “ABC Inc”;
}
}
public class Manager extends Employee implements Serializable {
String mgrId;
public static void main(String s[]) throws Exception {
Manager mgr = new Manager();
mgr.mgrId = “M001”;
mgr.name = “Jim”;
mgr.companyName = “XYZ Inc”;
// assume correct serialisation of mgr
// assume correct deserialization of mgr
System.out.println(mgr.mgrId+”,”+mgr.name+”,”+mgr.companyName);
}
}