Question 2
Back to Exercise
What is the output of the following Java program?
class Book {
String title = "untitled";
void Book() { title = "Java"; } // looks like a constructor, but it is a method
}
public class Main {
public static void main(String[] args) {
Book b = new Book();
System.out.print(b.title + " ");
b.Book();
System.out.println(b.title);
}
}
- A untitled Java Correct
- B Java Java
- C untitled untitled
- D Compilation error
Correct Answer: Option A
With a return type it is an ordinary method that happens to share the class name; new uses the default constructor. (Legal, but a terrible idea.)
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!