为什么我不必导入刚在主类中使用的类? (Java) [英] Why don't I have to import a class I just made to use it in my main class? (Java)

查看:48
本文介绍了为什么我不必导入刚在主类中使用的类? (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Deitel的书《 Java How to Program》第8版(早期对象版本)学习Java。

I am currently learning Java using the Deitel's book Java How to Program 8th edition (early objects version).

我在有关创建类和方法的章节中。

I am on the chapter on creating classes and methods.

但是,我对那里提供的示例感到非常困惑,因为它包含两个单独的.java文件,并且当其中一个使用另一个方法时,它确实不导入类。它只是从另一个.java文件创建了该类的对象,而没有先导入它。

However, I got really confused by the example provided there because it consists of two separate .java files and when one of them uses a method from the other one, it did not import the class. It just created an object of that class from the other .java file without importing it first.

这是如何工作的?为什么我不需要导入它?

How does that work? Why don't I need to import it?

这是书中的代码(我删除了大多数注释,以节省键入时间/空间...): b $ b .java类:

Here is the code from the book (I removed most comments, to save typing space/time...): .java class:

//GradeBook.java

public class GradeBook
{
    public void displayMessage()
    {
        System.out.printf( "Welcome to the grade book!" );
    }
}

.java主文件:

//GradeBookTest.java

public class GradeBookTest
{
    public static void main( String[] args)
    {
        GradeBook myGradeBook = new GradeBook();
        myGradeBook.displayMessage(); 
    }
}

我以为我必须写

import GradeBook.java;

或类似的东西。
如果我们不导入该类,编译器如何知道在哪里找到GradeBook类及其方法,以及如何知道该类是否存在?

or something like that. How does the compiler know where GradeBook class and its methods are found and how does it know if it exists at all if we dont import that class?

I进行了大量谷歌搜索,但没有找到答案。
我是编程的新手,所以请容忍我的新手问题。

I did lots of Googling but found no answer. I am new to programming so please tolerate my newbie question.

预先感谢您。

推荐答案

这是因为两者都在同一个程序包(文件夹)中。它们是自动导入的,无需为此编写导入语句。

It is because both are in same package(folder). They are automatically imported no need to write import statement for that.

这篇关于为什么我不必导入刚在主类中使用的类? (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆