[英]Java - object of a private inner class being as an argument to an outer class' constructor
public class Person
{
private class Date
{
public Date(int month, int day, int year)
{
...
}
}
private String name;
private Date birthDate;
public Person(String name, Date birthDate)
{
...
}
}
Above, I have an outer class, Person, and a private inner class, Date. 上面,我有一个外部类,Person和一个私有内部类Date。 The constructor for a Person object should take Date as one of its arguments. Person对象的构造函数应该将Date作为其参数之一。
public class Test
{
public static void main(String[] args)
{
Person testPerson = new Person("Mr. Sandman", new Date(1, 1, 1970));
}
}
But when I attempt to create a Person object in my separate "testing" file, Test.java, (above) (which is located in the same folder as my Person.java file), I get an error. 但是当我尝试在单独的“测试”文件Test.java(上面)(与我的Person.java文件位于同一文件夹中)中创建一个Person对象时,我收到一个错误。
The error is this: "error: no suitable constructor found for Person(String,Date)" (The compiler references the line on which I instantiate testPerson as the cause of the error.) 错误是这样的:“错误:没有为Person(String,Date)找到合适的构造函数”(编译器引用我在其上实例化testPerson作为错误原因的行。)
The question: What am I doing wrong? 问题:我做错了什么? Also, how can I create a Person object and pass a Date object into Person's constructor? 另外,如何创建Person对象并将Date对象传递给Person的构造函数? (Is this even possible if Date is a private inner class of Person?) (如果Date是Person的私有内部类,这甚至可能吗?)
Date
is a private inner class of Person
, so you are not going to be able to create an instance of it from another (non-Person) class. Date
是Person
的私有内部类,因此您无法从另一个(非Person)类创建它的实例。 Two things: 两件事情:
Date
from private to public 为了使您当前的设计有效,请将Date
的访问权限从私有更改为公共 Person
class, since you need an instance of it to create the inner class. 您还需要为Person
类创建一个默认构造函数,因为您需要一个实例来创建内部类。 Date
class in the SDK. SDK中已有Date
类。 To be honest, you should just create your Date
as a standalone class, as others have suggested. 说实话,你应该像其他人所建议的那样,将你的Date
创建为一个独立的类。
You could add a new Person
constructor that takes a java.util.Date
as it's second parameter and create a Person.Date
object from the java.util.Date
object (probably via a Calendar
object). 您可以添加一个新的Person
构造函数,它将java.util.Date
作为它的第二个参数,并从java.util.Date
对象创建一个Person.Date
对象(可能通过Calendar
对象)。
You may as well also make you existing constructor private
as no-one is ever going to be able to use it. 您也可以将现有构造函数设为private
因为没有人能够使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.