这是我的第一个代码放在名为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);
^
请帮我纠正并正确运行。 真诚的问候。
答案 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
是目录,certification
和other
是包。所以这些类应该被称为certification.Parent
和other.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
这应该有用。