Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, compilation error, Constructors

I have been trying a mock ocjp 6 test. I went though a question asking if the constructor is correct :

 1- public Test8(){}
 2- private void Test8(){}
 3- protected Test8(int k){}
 4- Test8(){}

The correct answer was 1 and 3. I didn't understand why the 4 was incorrect. When I tested the following code:

public class Test8 {
    Test8() {}

    public Test8() {}

}

I have compilation error, but when I remove one of the constructors if compile without any issue.

Someone can clear it up for me please.

like image 419
oueslatibilel Avatar asked May 19 '15 14:05

oueslatibilel


1 Answers

The confusing this about this stackoverflow question is that it's about another question. So when people answer referring to the "question" it's unclear which.


For your question about why this won't compile, it's because they both have the same signature (method name and params). Return type and visibility (public, private, protected) don't matter for making unique signatures.

public class Test8 {
    Test8() {}

    public Test8() {}
}

Because those both have the same name and parameter types they're the same method as far as the compiler is concerned, and that is why it worked when you removed one because it didn't have a duplicate.


As for the test question

Q8: Which of the following are valid Constructors?

  1. public Test8(){}
  2. private void Test8(){}
  3. protected Test8(int k){}
  4. Test8(){}

the only invalid one is 2 because it has a return type (void) listed. Constructors don't have return types. The site lists the correct answer as 1 and 3 though.

Q8:

  • 1 is correct. public Test8(){}.
  • 3 is correct. protected Test8(int k){}.

Why?

  • Possibly they put them all in a java file and tried to compile it like you and thought the 4 was invalid.
  • Maybe they think constructors need a visibility modifier?
  • Perhaps it's a terribly worded question and they meant "which of these can be used together starting from the top, ones below the cause the compilation to fail are incorrect"

No matter how you slice it, the question/answer on that site are poor.

like image 128
Captain Man Avatar answered Sep 20 '22 13:09

Captain Man