I'm new to Java and I've been asking myself if you could actually declare a method like a constructor (without a return type, neither void
) or that's why they are called constructors?
Asked
Active
Viewed 68 times
-5

Mateaș Mario
- 77
- 1
- 6
-
2Only constructors don't have a return type. – Eran Jan 11 '18 at 12:02
-
Have you tried it? Was the result not clear already? – Tom Jan 11 '18 at 12:02
-
You can not. Every method must have a returntype – Jens Jan 11 '18 at 12:02
-
A constructor is declared with the name of its declaring class. If you try and declare a method without a return type, you'll just get a compile error. – khelwood Jan 11 '18 at 12:02
-
Here good answer provided by @Dathan https://stackoverflow.com/questions/1788312/why-do-constructors-not-return-values – ArifMustafa Jan 11 '18 at 12:03
2 Answers
2
The constructor exists to build the object, it's not a method.
Methods need a return type because they return something from an existing object (even if the return type is void) but the constructor serves to build the object so it doesn't need any return type because the object doesn't exist when it is called.

Viktor Mellgren
- 4,318
- 3
- 42
- 75

Mouse
- 21
- 1
- 4
-
While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Viktor Mellgren Jan 11 '18 at 12:51
1
Java has a strict syntax, also for Method Declarations and Constructor Declarations.
And the syntax for a method always requires a return type or void. And the constructor is only valid if it has the same name as the class.
So for your example:
class Dog {
public Dog() { // constructor for the class Dog
}
public void Dog() { // method with the name Dog
}
public void method() { // method with the name method
}
// invalid code
// causes an error because the return type for the method is missing
// and isn't a constructor because it hasn't the same name as the class.
public method() {
}
}