java如何在其他包中使用类? [英] java how to use classes in other package?

查看:393
本文介绍了java如何在其他包中使用类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


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

我想要主类的主要功能来调用函数x在第二类。
我该怎么办?我试过了:

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

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.

推荐答案

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

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();  
   }
}

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

还有另一种选择,正如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:

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 = ...;
    }
}

这篇关于java如何在其他包中使用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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