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?
public Test8(){}
private void Test8(){}
protected Test8(int k){}
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.
4
that I can think of is that it ispackage private
, meaning it cannot be used outside thepackage
it is declared in, which is unusual but could be deliberate. – Pennypennyaliner