$ 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
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Constructors cannot return a value; they return the constructed object, so to speak.
You get an error because the compiler is looking for a constructor that takes a string as its argument. Since you did not declare a constructor the only constructor available is the default constructor that does not take any argument.
Why do I say you did not declare a constructor? Because as soon as you declare a return value/type for your method it is not a constructor anymore but a regular method.
From the Java Documentation:
If you elaborate what you are trying to achieve someone might be able to tell you how you can get to that goal.
A constructor can't have a return value like a "normal" function. It is called when an istance of the class in question is created. It is used to perform the initialization of that instance.
I think the best way to produce the effect you want would be the following:
This replaces the
public String Const()
method you used previously, and by overriding thepublic String toString()
method ofObject
(Which all Java classes inherit from) the String value of the object is printed correctly when you want to print the object, so your main method remains unchanged.Actually Constructor in a java class can't return a value it must be in the following form
check these links http://leepoint.net/notes-java/oop/constructors/constructor.html http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html
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. So we say explicitely constructor does not have a return value.