This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
Question 21 What will happen if you compile/run the following code? 1: public class Q21 2: { 3: int maxElements; 4: 5: void Q21() 6: { 7: maxElements = 100; 8: System.out.println(maxElements); 9: } 10: 11: Q21(int i) 12: { 13: maxElements = i; 14: System.out.println(maxElements); 15: } 16: 17: public static void main(String[] args) 18: { 19: Q21 a = new Q21(); 20: Q21 b = new Q21(999); 21: } 22: } A) Prints 100 and 999. B) Prints 999 and 100. C) Compilation error at line 3, variable maxElements was not initialized. D) Compillation error at line 19. Answer : D Explanation : Constructors should not return any value. Java won't allow to indicate with void. In this case void Q21() is an ordinary method which has the same name of the Class.
Can anyone help me to explain more detail on this answer?
Roopa Bagur
Ranch Hand
Joined: Nov 03, 2000
Posts: 267
posted
0
D is the correct answer.. Here is what happens.. Constructors do not have return type. If you have a method which has the same name as the class & which has a return type..it is not a constructor but just another method which happens to have the same name of the class. In the following code you have only constructor Q21(int i). void Q21()is a method because it has a return type of void. At line 19 Q21 a = new Q21();
you are trying to create a object using the default constructor.What you have to remember here is when you don't have any constructors for a class the compiler adds a default constructor(no argument constructor) to the class otherwise it is your responsibility to add constructors including the no argument constructor to the class. Hope this helps.
Originally posted by SteffySY Sing: Question 21 What will happen if you compile/run the following code? 1: public class Q21 2: { 3: int maxElements; 4: 5: void Q21() 6: { 7: maxElements = 100; 8: System.out.println(maxElements); 9: } 10: 11: Q21(int i) 12: { 13: maxElements = i; 14: System.out.println(maxElements); 15: } 16: 17: public static void main(String[] args) 18: { 19: Q21 a = new Q21(); 20: Q21 b = new Q21(999); 21: } 22: } A) Prints 100 and 999. B) Prints 999 and 100. C) Compilation error at line 3, variable maxElements was not initialized. D) Compillation error at line 19. Answer : D Explanation : Constructors should not return any value. Java won't allow to indicate with void. In this case void Q21() is an ordinary method which has the same name of the Class.
Can anyone help me to explain more detail on this answer?
sing
Ranch Hand
Joined: Nov 29, 2001
Posts: 121
posted
0
Hi Roopa, Oop! "Constructors do not have return type." means included void return. Thank you very much! Steffy