$ cat Const.java
public class Const {
String Const(String hello) {
return hello;
}
public static void main(String[] args) {
System.out.println(new Const("Hello!"));
}
}
$ javac Const.java
Const.java:7: cannot find symbol
symbol : constructor Const(java.lang.String)
location: class Const
System.out.println(new Const("Hello!"));
^
1 error
No, constructor does not return any value. While declaring a constructor you will not have anything like return type. In general, Constructor is implicitly called at the time of instantiation. And it is not a method, its sole purpose is to initialize the instance variables.
A constructor can not return a value because a constructor implicitly returns the reference ID of an object, and since a constructor is also a method and a method can't return more than one values.
No, constructor does not have any return type in Java. Constructor looks like method but it is not. It does not have a return type and its name is same as the class name. Mostly it is used to instantiate the instance variables of a class.
Constructors do not return any type while method(s) have the return type or void if does not return any value. Constructors are called only once at the time of Object creation while method(s) can be called any number of times.
What you've defined isn't actually a constructor, but a method called Const
. If you changed your code to something like this, it would work:
Const c = new Const();
System.out.println( c.Const( "Hello!" ) );
If no specific constructor is explicitly defined, the compiler automatically creates a no-argument constructor.
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