如何在apackage中编译和运行一个类,该类从另一个包中的另一个类继承受保护的成员

时间:2013-07-16 06:13:06

标签: java

这是我的第一个代码放在名为certification

的目录中
package certification;
    class Parent{
        protected int x=9;//protected access
    }

这是我的另一个代码放在另一个名为other

的目录中
package other;
    import certification.Parent;
    class Child extends Parent{
    public void testIt(){
    System.out.println("x is" + x);
        }
    public static void main(String args[]){
        Child n=new Child();
        n.testIt();
      }
}

但问题是每当我尝试编译类Child时,编译器会给出以下错误 Child.java:2:包认证不存在

import certification.Parent;
                ^

Child.java:3:找不到符号 符号:class Parent

class Child extends Parent{
                ^

Child.java:5:找不到符号 符号:变量x 位置:class other.Child

System.out.println("x is" + x);
                        ^

请帮我纠正并正确运行。 真诚的问候。

5 个答案:

答案 0 :(得分:2)

以下内容需要改变;

public class Parent{  //parent class should be public
    protected int x=9;//protected access
}

    Child n=new Child();
    n.testIt(); // not m.voidtestIt();

答案 1 :(得分:1)

因为Child类在不同的包中; Parent类需要public才能继承。将Parent公开为

public class Parent {

并修复Child#main()方法中的拼写错误 n。 void testIt(); 。然后假设以下目录结构

/src/other/Child.java
/src/certification/Parent.java

Child.java内的/编译为

/$ javac -cp src -d bin src/other/Child.java

这应该在

创建.class文件
/bin/other/Child.class

编辑
编译完成后,从/作为

运行
/$ java -cp bin other.Child

答案 2 :(得分:1)

说你的文件夹结构是这样的

sources/certification/Parent.java
sources/other/Child.java

另外,将Parent课程设为public,因为我们正试图在课程外访问它。 另外,Child类应该调用n.testIt()而不是n.voidTestIt()。 void是返回类型。

课程将

package certification;
   public class Parent{
        protected int x=9;//protected access
    }


package other;
import certification.Parent;
    class Child extends Parent{
    public void testIt(){
    System.out.println("x is" + x);
        }
    public static void main(String args[]){
        Child n = new Child();
        n.testIt();
      }
}

请按照以下步骤操作。

  • 使用sources
  • 导航至cd sources目录
  • 首先编译Parent类,因为Child类需要使用命令javac certification/Parent.java
  • 然后使用javac -classpath . other/Child.java编译Child类。这里-classpath是告诉javac命令从何处选择Child.java所需的类的选项,而.是当前目录,即我们的类路径,即sources
  • 编译成功后,使用Child运行java other.Child课程。这里我们使用Child的完全限定名称。

只需导航到您的C盘并执行此操作

C:\>cd sources

C:\sources>javac certification/Parent.java

C:\sources>javac -classpath . other/Child.java

C:\sources>java other.Child
x is9

C:\sources>

理想情况下,您应始终从目录结构的空间编译和启动java类。 java文件中的包名是目录结构。在编译时,它们被视为java文件,因此在编译时使用目录结构。 certification/Parent.java 。但是在编译类时,使用包名称标识类文件。因此,请使用根目录中的完全限定名称,即包结构开始的位置。在我们的示例中,sources是目录,certificationother是包。所以这些类应该被称为certification.Parentother.Child

答案 3 :(得分:0)

您希望在根目录下编译Child.java(在许多情况下应该是src)并使用路径进行编译,类似于此假设从您的包名称开始:

javac other/Child.java

答案 4 :(得分:0)

您的类路径应设置为认证的父文件夹。通常,你会有一个'src'文件夹,其中包含你的包结构。

1)cd到'src'文件夹。
2)将此类路径设置为SET CLASSPATH=%CLASSPATH%;.;
3)将您的父母编译为javac certification\Parent.java
4)将您的孩子编译为javac other\Child.java

这应该有用。