Java 如何通过外部类构造函数访问内部类?
我正在尝试使用我的主代码中的person构造函数创建一个personJava 如何通过外部类构造函数访问内部类?,java,Java,我正在尝试使用我的主代码中的person构造函数创建一个person Person outerClass = new Person("Anon", new Date(06,03,1991), null); 但是它说它找不到上课日期。我是否正确地填充了这个构造函数并调用了类间函数 public class Person implements Cloneable { private String name; private Date born;
Person outerClass = new Person("Anon", new Date(06,03,1991), null);
但是它说它找不到上课日期。我是否正确地填充了这个构造函数并调用了类间函数
public class Person implements Cloneable
{
private String name;
private Date born;
private Date died;//null indicates still alive.
public Person(String initialName, Date birthDate, Date deathDate)
{
if (consistent(birthDate, deathDate))
{
name = initialName;
born = new Date(birthDate);
if (deathDate == null)
died = null;
else
died = new Date(deathDate);
}
else
{
System.out.println("Inconsistent dates. Aborting.");
System.exit(0);
}
}
private class Date
{
private String month;
private int day;
private int year; //a four digit number.
public Date( )
{
month = "January";
day = 1;
year = 1000;
}
public Date(int monthInt, int day, int year)
{
setDate(monthInt, day, year);
}
因为您的需求需要一个内部类,所以让我们把
Date
作为Person
的内部类是否合适的问题放在一边
它找不到类日期
,因为它是私有的。然而,即使它是公共的,您仍然无法实例化它,因为您首先需要一个人的实例。一种方法是从构造函数中删除Date
参数,并改用mutators。e、 g:
public class Person {
private final String name;
private Date birthDate;
public class Date {
private final int year, month, day;
public Date(final int year, final int month, final int day) {
this.year = year;
this.month = month;
this.day = day;
}
public String toString() {
// look at me, I can access attributes of the enclosing Person
return name + " is associated with the year " + year;
}
}
public Person(final String name) {
this.name = name;
}
public void setBirthDate(final Date birthDate) {
this.birthDate = birthDate;
}
public static final void main(final String... arguments) throws Exception {
final Person person = new Person("name");
final Date birthDate = person.new Date(2015, 11, 9);
person.setBirthDate(birthDate);
}
}
但是,如果内部类独立于外部类的实例存在是有意义的,那么它应该是静态的。这将允许您自己实例化日期
,而无需现有的人员
。e、 g:
public class Person {
private final String name;
private final Date birthDate;
public static class Date {
private final int year, month, day;
public Date(final int year, final int month, final int day) {
this.year = year;
this.month = month;
this.day = day;
}
public String toString() {
// I do not know about any Person
return "year: " + year;
}
}
public Person(final String name, final Date birthDate) {
this.name = name;
this.birthDate = birthDate;
}
public static final void main(final String... arguments) throws Exception {
final Person person = new Person("name", new Date(2015, 11, 9));
}
}
注意,这在功能上与将Date
声明为自己的顶级类相同,只是现在完全限定的类名以“Person.Date”结尾。为什么以万圣之名将Date作为私有内部类??为什么不简单地将其作为一个独立的公共类(尽管更改其名称以避免与java.util.Date
混淆)?这也是我的想法,但作业要求它:/Show实际的完整要求。你可能误解了它们。你对内部类了解多少?内部类需要其声明类的实例。那么,在不引用newperson
实例的情况下,如何创建newdate
实例呢?重做类Person,使类日期成为类Person的私有内部类。另外,做一个合适的测试程序。