-5

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?

Mateaș Mario
  • 77
  • 1
  • 6

2 Answers2

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() {
    }
}