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

标签 java

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

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/

相关文章:

java - 如何让 TreeMap 以数组为键工作?

java - 还有什么方法可以倒带队列?

java - String.valueOf(int) , `+` 字符串运算符和 Integer.toString(int) 之间的区别

java - 如何构建 Apache Commons Lang Range<Integer> 对象?

java - 使用两个值 x 和 y 对 java 中的数组进行自定义排序

java - 使用 Java gcm-server 向主题发送消息

java - 执行服务。所有线程完成后如何获得结果?

用于双重工作的 Java 循环

java - Spring MVC 简介

Java - 将 select 语句的结果存储在 arraylist 中是好还是坏方法?