简体   繁体   中英

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. The constructor for a Person object should take Date as one of its arguments.

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.

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.)

The question: What am I doing wrong? Also, how can I create a Person object and pass a Date object into Person's constructor? (Is this even possible if Date is a private inner class of 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. Two things:

  • In order to make your current design work, change the access of Date from private to public
  • You will also need to create a default constructor for the Person class, since you need an instance of it to create the inner class.
  • Please consider changing your inner class name. There is already a Date class in the SDK.

To be honest, you should just create your Date as a standalone class, as others have suggested.

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).

You may as well also make you existing constructor private as no-one is ever going to be able to use it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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