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

编程入门 行业动态 更新时间:2024-10-27 03:39:38
本文介绍了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如何在其他包中使用类?

本文发布于:2023-07-16 16:08:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1123410.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:包中   如何在   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!