Reputation: 13
public class Person {
public String Person(String name) {
return name;
}
public static void main(String[] args) {
Person one = new Person("hendry");
}
}
What am I doing wrong?
Upvotes: 0
Views: 59
Reputation: 292
Constructor returns nothing. They can take parameter but they don't return anything. It must be like this:
private String name;
public Person(String name) {
this.name = name; }
public String getName(){
return this.name; }
public static void main(String[] args) {
Person one = new Person("hendry");
String name = one.getName();
}
Upvotes: 0
Reputation: 843
public String Person(String) is not valid constructor as constructors dont have return type. So actually as per compiler there is no parameterized constructor in your code but you are trying to call one
Upvotes: 0
Reputation: 34146
Constructors don't have a return type. Why? Because their purpose of existing is to initialize attributes.
Maybe what you are looking for is a getter method:
public String getPerson(String name) {
return name;
}
But if you want it as constructor, to initialize an attribute, first declare it, and then assign the parameter of the constructor to it:
public class Person {
private String name;
public String Person(String pName) {
this.name = pName;
}
...
}
Upvotes: 0
Reputation: 178253
This is not a constructor, because you have declared a return type. It's just a method that happens to have the same name as your class.
public String Person(String name) {
Without an explicit constructor, the compiler inserts an implicit default constructor with no parameters, so there is a conflict with the number of arguments.
Remove the return type; no return type should be specified on constructors, not even void
:
public Person(String name)
Don't return anything from the constructor. But, you may wish to store the parameter in an instance variable, and you may wish to add a method that returns that instance variable (a "getter").
Upvotes: 2