Java Programming - Declarations and Access Control - Discussion

Discussion Forum : Declarations and Access Control - Finding the output (Q.No. 3)
What will be the output of the program?
public class A
    void A() /* Line 3 */
        System.out.println("Class A"); 
    public static void main(String[] args) 
        new A(); 
Class A
Compilation fails.
An exception is thrown at line 3.
The code executes with no output.
Answer: Option

Option D is correct. The specification at line 3 is for a method and not a constructor and this method is never called therefore there is no output. The constructor that is called is the default constructor.

15 comments Page 1 of 2.

Ayylmao said:   7 years ago
This is easy, get the constructor basics right first.

Like everyone said a constructor doesn't have a return type.
Therefore void A(){//code}, int A(){//code}, float A(){//code} ,etc. are all methods where as,
A(){//code} is a constructor

Therefore in the given code, just remove 'void' and i'll become a constructor and print "Class A" otherwise it won't do anything.

Alexandre said:   7 years ago
For me, the answer is "B" Compilations fails, because the compiler by Eclipse gives me this message (before compile, I can't compile).

"This method has a constructor name".

Ishu said:   8 years ago
Constructor don't have return type and in this problem there is return type which is void A() so this is a method and int his very question method name is also with same name as class so block will not execute.

Aqueenni said:   9 years ago
As per my knowledge, method name starts with a lowercase.

Here it is void A().

So one can also think that it is a constructor declared wrongly and hence the option B. Compilation fails.

Sandeep Tomar said:   10 years ago
If we are allowed to have method with same name. How Compiler will come to know whether we have written a valid function code or a wrong constructor code. Please help to clarify on this. Thanks.

Mahi said:   10 years ago
class a
void a(){}

is both of the methods are constructor of class a, if not why?

Dilly said:   10 years ago
Unlike C++ in Java we can have method name same as of class name.

But like C++ constructor doesn't have return type not even void.

Pramod pai said:   10 years ago
Constructor can only initialize like:

void A(int a)

Where as method will have statements:

void A
print...(bla bla bla);


Hope you're clear.

Sravan said:   10 years ago
A() is a method not a constructor. So, the anonymous object created is not calling method A(). The code will execute without any output.

Gtrbt said:   1 decade ago
Because constructor doesn't specify return type.

Post your comments here:

Your comments will be displayed after verification.