czlsws
czlsws

Reputation: 133

Why could a java class use another class under the same package directly without explicitly importing that class?

I am using sts to build my first project.

there are 2 classes in there, FirstProApplication created by the guide, Alien created manually.

enter image description here

here is all the content in FirstProApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class FirstProApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(FirstProApplication.class, args);
        System.out.print("hi, boot");
        Alien a = context.getBean(Alien.class);
    }

}

question

why could FirstProApplication use Alien directly without explicitly importing the class, is this a JVM feature search or the IDE did something background?

Upvotes: 0

Views: 278

Answers (1)

user10762593
user10762593

Reputation:

The answer is "because it's the same package".

It's neither a JVM feature nor an IDE feature, it's in the definition of the language.

Furthermore, you don't actually have to import a class to use it. You could for example use the fully-qualified names to write

java.util.List foo<String> = new java.util.ArrayList<>();

Importing makes the 'simple names' visible. From this point of view, you can regard that the 'package name' is used to form the fully-qualified name for types that are neither explicitly declared nor explicitly imported into the current compilation unit.

Upvotes: 4

Related Questions