Search code examples
javaconstructorprivateinner-classes

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


Solution

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