gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:40:31 26 4
gpt4 key购买 nike

我可以导入,使用其他包中的类吗?在 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:

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

但他们都没有工作。我现在想不通了。

最佳答案

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

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

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

package com.my.stuff.mainimport com.my.stuff.second.Second;   // THIS IS THE IMPORTANT LINE FOR YOUR QUESTIONclass Main {   public static void main(String[] args) {      Second second = new Second();      second.x();     }}

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

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

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

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

关于java如何使用其他包中的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3480389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com