简体   繁体   English

构造函数错误,找不到

[英]constructor error , cannot find

it says cannot find Constructor Person() in class person, but i have class person. 它说在类人中找不到构造函数Person(),但是我有类人。 heres my code 这是我的代码

public class Person{

    private String name;
    private int age;
    public String details;

    public Person(final String name, final int age){
        this.name = name;
        this.age = age;
    }
}

and the test person class 和测试人类

public class TestPerson{
    public static void main(String args[]){
        int q;
        System.out.println(args.length + "objects created");
        for(q = 1; q < args.length; q++){
            final Person p1 = new Person();
            for(int x = 0; x < args[q].length(); x++){
                args[q].split(",");
                p1.setDetails(name, age);
                System.out.println(p1);
            }
        }
    }
}
Person p1 = new Person();

This line fails because you have defined a constructor with parameters (and no constructor without parameters). 该行失败,因为您定义了带有参数的构造函数(并且没有参数的构造函数也没有)。 If you don't define any constructor for your class, the compiler inserts an empty default constructor. 如果您没有为类定义任何构造函数,则编译器将插入一个空的默认构造函数。 But if you define any constructor at all, the compiler doesn't insert a default constructor, and it's up to you to provide the constructors you need. 但是,如果您完全定义了任何构造函数,则编译器不会插入默认的构造函数,而是由您提供所需的构造函数。

Read these articles from the Sun Java Tutorial : 阅读《 Sun Java教程》中的这些文章:

Your Person constructor requires two parameters. 您的Person构造函数需要两个参数。 You have to pass two arguments when you call it in your test program. 在测试程序中调用它时,必须传递两个参数。

Or you could create a second constructor that takes no arguments in your Person class. 或者,您可以创建第二个构造函数,该构造函数在Person类中不包含任何参数。

You declared the Person constructor to require two args. 您声明了Person构造函数需要两个参数。 Pass it two args. 传递两个参数。

the constructor is 构造函数是

public Person(String name, int age)

so you cannot call 所以你不能打电话

Person p1 = new Person();

but

Person p1 = new Person(name, age);

Of course, you need to define name and age first, which your program never seems to do... 当然,您需要先定义名称年龄 ,而程序似乎从来没有这样做过。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM