Question:
!Good!
I'm studying, and preparing for the Java 8 OCA certification. There is an example 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 the C , because in the
main
although aWriter
class object is being created, aProgrammer
type is being stored, and for this reason it should take theWriting code
. Although it is true that the methods do not have@override
, but I did not know to what extent it can influence.
Answer:
By creating an instance of Programmer
and calling the write()
method,
Writer w = new Programmer();
w.write();
The Programmer
class extends the Writer
class which contains a static method, which in this case cannot be overloaded, so this will be the message to print.
abstract class Writer {
public static void write() {
System.out.println("Writing...");
}
}
Exit:
Writing...
Therefore, the answer is A)
In the case where the write()
methods were not static, the output would be
Writing code
the Author class is not used:
class Author extends Writer {
public static void write() {
System.out.println("Writing book");
}
}