!Good!
I am studying, and preparing for the OCA Java 8 certification. There is a sample question that I don't quite understand... Which gives me this piece of code:
abstract class Writer {
public static void write() {
System.out.println("Writing...");
}
}
class Author extends Writer {
public static void write() {
System.out.println("Writing book");
}
}
public class Programmer extends Writer {
public static void write() {
System.out.println("Writing code");
}
public static void main(String[] args) {
Writer w = new Programmer();
w.write();
}
}
And I have to choose the correct answer among these, to know what the result of the program would be:
A) Writing... B) Writing book C) Writing code D) Compilation fails.
According to the results provided by Oracle, the correct one would be A .
But why?
I thought it was C , but apparently not...
EDIT
I answer C , because
main
even though a class object is being created inWriter
it, a type is being storedProgrammer
, and therefore it should take theWriting code
. Although it is true that the methods do not lead@override
, but I did not know to what extent it can influence.
By creating an instance of
Programmer
and calling the methodwrite()
,The class
Programmer
extends the classWriter
which contains a static method, which in this case cannot be overloaded, so this will be the message to print.Departure:
Therefore, the answer is A)
In the case in which the methods
write()
were not static, the output would bethe Author class is not used:
The answer is A because if you look at the method
write
it is static and when you call it with the type object youWriter
call the static method of the class which would be the equivalent of writingA) Because static methods cannot be overloaded.
In Java, the binding is the association between the call of a method with the code of said method. There are two types of binding:
Static or Early, which is done at compile time. Static, private, and final methods are bound here.
Dynamic or Late, which occurs at runtime. The instance methods including the overrides are bound here.
It cannot be C, because the compilation will not fail, however it would issue a Warning saying that the static methods must be called statically, that is, from the class and not from a class instance.