Je Moeder
Je Moeder

Reputation: 13

Constructor undefined issue

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

Answers (4)

OmerFaruk
OmerFaruk

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

Rusheel Jain
Rusheel Jain

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

Christian Tapia
Christian Tapia

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

rgettman
rgettman

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

Related Questions