Java, compilation error, constructors

I tried mock ocjp 6 test. I went asking the question 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 did not understand why 4 was incorrect. When I tested the following code:

 public class Test8 { Test8() {} public Test8() {} } 

I have a compilation error, but when I delete one of the constructors when compiling without any problems.

Someone can clarify this for me, please.

+7
java visibility constructor scjp
source share
3 answers

Confused about this question, the stack question is that this is another question. Therefore, when people answer the question "question", it is not clear which one.


On your question about why this will not compile, this is because they both have the same signature (method name and parameters). The return type and visibility ( public , private , protected ) are not important for creating unique signatures.

 public class Test8 { Test8() {} public Test8() {} } 

Since they both have the same name and parameter types, they are the same method as in the compiler, and that is why it worked when you deleted it because it did not have a duplicate.


Regarding the test question

Q8: Which of the following valid constructors?

  • public Test8(){}
  • private void Test8(){}
  • protected Test8(int k){}
  • Test8(){}

the only invalid is 2 , because it has a return type ( void ). Constructors do not have return types. The correct answer is indicated on the site as 1 and 3 .

Q8:

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

Why?

  • Perhaps they put them all in a java file and tried to compile it like you did, and thought 4 invalid.
  • Maybe they think designers need a visibility modifier?
  • Perhaps this is a terribly worded question, and they mean, "which ones can be used together, starting at the top, lower than the reason the compilation failed"

No matter how you cut it, the question / answer on this site is bad.

+7
source share

The only reasonable answer is the wrong answer key exam layout. 1, 3, and 4 are valid constructors. It might be wrong to have 1 and 4 as constructors for the same class, but the question did not ask about it.

+2
source share

You cannot re-declare the same constructor with the same arguments (in this case, no arguments)

First you define a private constructor. Then you define a public constructor, but with the same number of arguments.

You need to choose whether you want to create a private or public constructor.

 public class Test8 { Test8() {}// Or this one public Test8() {} // Or this one. but not both. } 
0
source share

All Articles