To add to what Dave has - correctly - said: the only time you can declare a method without a return type is when the method name is the same as the class name: when it is a
constructor
, and that's because the return type of a
constructor
can only ever be an instance of the class type.
A
constructor
is a special method that is never called directly - it can only be called when you instantiate a class by using the
new
keyword:
public class MyClass
{
public MyClass()
{
...
}
}
...
MyClass x = new MyClass();
The only exception to that is when the
constructor
is
static
- then it is never called directly, but called by the system at some point prior to the first usage of the class.
If you omit the return type to a "normal" method, the system assumes you wanted to create a constructor, but then complains because it can't work out when to call it.