java如何使用其他包中的类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3480389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:09:40  来源:igfitidea点击:

java how to use classes in other package?

java

提问by ace

can I import,use class from other package? In Eclipse I made 2 packages one is main other is second

我可以导入,使用其他包中的类吗?在 Eclipse 中,我制作了 2 个包,一个是主要的,另一个是第二个

main
 -main (class)
second
 -second (class)

and I wanted the main function of main class to call the function x in second class. how can I do it? I tried:

我希望主类的主函数调用第二类中的函数 x。我该怎么做?我试过:

import second; 
second.x(); (if both classes are in the same package then it works)
second.second.x();

but none of them worked. I'm out of idea now.

但他们都没有工作。我现在没主意了。

采纳答案by atk

You have to provide the full path that you want to import.

您必须提供要导入的完整路径。

import com.my.stuff.main.Main;
import com.my.stuff.second.*;

So, in your main class, you'd have:

因此,在您的主要课程中,您将拥有:

package com.my.stuff.main

import com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTION

class Main {
   public static void main(String[] args) {
      Second second = new Second();
      second.x();  
   }
}

EDIT: adding example in response to Shawn D's comment

编辑:添加示例以响应 Shawn D 的评论

There is another alternative, as Shawn D points out, where you can specify the full package name of the object that you want to use. This is very useful in two locations. First, if you're using the class exactly once:

正如 Shawn D 指出的那样,还有另一种选择,您可以在其中指定要使用的对象的完整包名称。这在两个位置非常有用。首先,如果您只使用该类一次:

class Main {
    void function() {
        int x = my.package.heirarchy.Foo.aStaticMethod();

        another.package.heirarchy.Baz b = new another.package.heirarchy.Bax();
    }
}

Alternatively, this is useful when you want to differentiate between two classes with the same short name:

或者,当您想区分具有相同短名称的两个类时,这很有用:

class Main {
    void function() {
        java.util.Date utilDate = ...;
        java.sql.Date sqlDate = ...;
    }
}

回答by Tim Reddy

Given your example, you need to add the following import in your main.mainclass:

鉴于您的示例,您需要在main.main类中添加以下导入:

import second.second;

Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

一些额外的建议,请确保您将类名命名为 Java 标准。因此,您的示例 Main 类将具有以下结构:

package main;  //lowercase package names
public class Main //titlecase class names
{
    //Main class content
}

回答by Pokuri

It should be like import package_name.Class_Name--> If you want to import a specific class (or)

应该是这样的import package_name.Class_Name--> 如果要导入特定的类(或)

import package_name.*--> To import all classes in a package

import package_name.*--> 导入一个包中的所有类