2016-04-21 76 views
-1

Person.java无法建立从自定义的类的对象

public class Person { 
    public String firstname; 
    public String lastname; 
    public Date dob; 
    public boolean sex; 

    public Person(String firstname, String lastname, Date dob, boolean sex){ 
     this.firstname = firstname; 
     this.lastname = lastname; 
     this.dob = dob; 
     this.sex = sex; 
    } 

    public Person(String firstname, String lastname, Date dob, String s){ 
     this.firstname = firstname; 
     this.lastname = lastname; 
     this.dob = dob; 
     if (s.charAt(0)=='f' || s.charAt(0)=='F') sex = true; else sex = false; 
    } 

Date.java

public class Date { 
    public int day; 
    public int month; 
    public int year; 

    public Date(int day, int month, int year) 
    { 
     this.day = day; 
     this.month = month; 
     this.year = year; 
    } 
} 

为什么这是错?我如何正确创建一个对象?这是来自一篇论文,所以上面的类不能改变。

public static void main(String[] args) { 
    Person person1 = new Person("Adeline", "Wells", (12,4,1992), false); 
} 
+0

什么是错?请在阅读本文之前询问:http://stackoverflow.com/help/how-to-ask – tak3shi

+0

请注意,您正在使用的Date构造函数已被弃用,并且整个Date类已过时(使用“Instant”代替)。此外,通过使用布尔值,你可以做出两个非显而易见的陷阱:人的性别是已知的(并且被宣布为男性/女性),并且一个性别(男性)映射到“真实”。 – chrylis

+0

您在'..new中缺少'new Date'新人(...'应该是'...“Wells”,新日期(12,4,1992)...' – Yazan

回答

1

的问题是,你的场日期为Person类是一类为好,这样你就这样做:

public static void main(String[] args) { 
    Date d = new Date(12,4,1992); 
    Person person1 = new Person("Aaron", "Wells", d, false); 
} 

否则,如果你想直接传递一天月份和年份,你可以做somenthig这样的:

public Person(String firstname, String lastname, int d, int m, int y, boolean sex){ 
     this.firstname = firstname; 
     this.lastname = lastname; 
     this.dob = new Date(d, m, y); 
     this.sex = sex; 
    } 

,然后现在你可以做

public static void main(String[] args) { 
    Person person1 = new Person("Adeline", "Wells", 12,4,1992, false); 
} 
+0

谢谢,是否绝对没有如何将它们全部放在一条线上? – Ken

0

你可以这样做在一行这样:

public static void main(String[] args) { 
    Person person1 = new Person("Aaron", "Wells", new Date(12,4,1992), false); 
}