Return to site

☕🎓JAVA CERTIFICATION QUESTION: null instance and static calls

· ocp,java

Given the following code:

What is the result? Choose one.

* Compilation fails.

* NullPointerException is thrown at runtime.

* ClassCastException is thrown at runtime.

* The following is printed:





* The following is printed:





#java #certificationquestion #ocp

var v = superS;

is identical in effect to the following explicit form

SuperS v = superS;

and, in this case, it has identical effect to this form

SuperS v = null;

Note the use of a reference variable (v), instead of a class name, as the prefix in an expression referring to a static element.

Static elements belong to the class, not to any particular instance of that class.

The compiler creates code that simply determines the target class and obtains the element from that.

This tells you that the value of the prefix object is entirely irrelevant because it plays no part in accessing static elements.

It doesn’t matter if the reference is the null value, because it’s never used.

Also, casting the value to the subtype and reassigning it, as in the following line, is also irrelevant:

v = (SubS) v;

An assignment like that might change the value of the variable (although here it does not),

but it cannot change the type of that variable, which is determined entirely by its declaration.

Indeed, nothing can change the type of a variable at runtime,

even though the cast on the right of the assignment does create a temporary expression that has the cast type.

From this, remembering that the type of the variable v is SuperS,

you can determine that the code will print the text from the SuperS class twice,

and it will never print the text from the SubS class.

The following is printed: