Java: How does a method operate on objects of unknown type?

Consider, the following three Java classes in three different packages:

User.java

package user;

public class User {

    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User [name=" + name + "]";
    }
}

UserFactory.java

package factory;

import user.User;

public class UserFactory {

    private static User user;

    public static User getUser() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

}

Test.java

package test;

import factory.UserFactory;

public class Test {
    public static void main(String[] args) {
        UserFactory.getUser().setName("StackOverflow");
        System.out.println(UserFactory.getUser());
    }
}

The main method belongs to class test.Test that doesn't import user.User class. However, it is able to operate on user.User type.

How to justify this behaviour?

Jon Skeet
people
quotationmark

The only purpose of an import statement is to allow you to use a type (or a method etc, for import static) without fully-specifying the name. It doesn't make the type available - it just makes it available by short name.

In this case, the UserFactory type is imported, and the compiler knows the exact type returned by UserFactory.getUser()... that type doesn't need to be named in the code that calls getUser().

If you wanted to write:

User u = UserFactory.getUser();

then you'd need the import... or you could just fully-qualify it:

user.User u = UserFactory.getUser();

But unless you need to refer to the type by short name within the source code, there's no need for an import statement.

people

See more on this question at Stackoverflow