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.
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?
4
was invalid.No matter how you slice it, the question/answer on that site are poor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With