在java中导入类文件 [英] import class file in java

查看:41
本文介绍了在java中导入类文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个主目录(包含 main.java)和一个子目录(包含 child.java).

I have a main directory (contains main.java) and a subdirectory( contains child.java).

我的问题是如何在main.java中实例化child.java

My problem is how to instantiate child.java in main.java

  1. 我已将子类设为公开.&将第 1 行添加为 package mypackage
  2. 我已经用 javac -d 编译了 child.class .child.java 创建一个新的 mypackage 目录.
  3. 我尝试在 main 中导入子类,如下所示:import subdirectory.mypackage.*(注意 -d 选项将 child.class 放在 mypackage 文件夹中)
  4. 我用javac main.java"编译了 main.java 文件
  1. I have made the child class public. & added the line#1 as package mypackage
  2. I have compiled child.class with javac -d . child.java which creates a new mypackage directory.
  3. I tried to import child class in main as follows: import subdirectory.mypackage.* (note -d option places the child.class inside mypackage folder)
  4. I compiled the main.java file with "javac main.java"

我收到以下错误:

mainAESE.java:9: cannot access subdirectory.child
bad class file: RegularFileObject[./subdirectory/child
class file contains wrong class: mypackage.child
Please remove or make sure it appears in the correct subdirectory of the class
child childInstance= new child();
^
1 error

请帮帮我!!

推荐答案

确保包文件夹 mypackageMain.class 共享父文件夹.

Be ensure that the package folder mypackage and Main.class share the parent folder.

package mypackage;
public class Child {}

我假设 Main 类是在 default 包中创建的.

I presume that the Main class is created in default package.

public class Main {
   public static void main(String []args){
         mypackage.Child child=new mypackage.Child();
   }
}

你的目录结构应该是:

main-directory/
              |
              |----/mypackage/
                            Child.class
              |
              | Main.class
              | Main.java
              | Child.java

并启动/加载 Main 发出以下命令,

and to launch/load the Main issue following command,

java主

这篇关于在java中导入类文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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