C:\Users\jaina_000\Desktop\learn_java\p1>javac Testp1.java Testp1.java:6: error: cannot find symbol Protection ob = new Protection(); ^ symbol: class Protection location: class Testp1 Testp1.java:6: error: cannot find symbol Protection ob = new Protection(); ^ symbol: class Protection location: class Testp1 Testp1.java:7: error: cannot find symbol Derived ob1 = new Derived(); ^ symbol: class Derived location: class Testp1 Testp1.java:7: error: cannot find symbol Derived ob1 = new Derived(); ^ symbol: class Derived location: class Testp1 Testp1.java:8: error: cannot find symbol SamePackage ob2 = new SamePackage(); ^ symbol: class SamePackage location: class Testp1 Testp1.java:8: error: cannot find symbol SamePackage ob2 = new SamePackage(); ^ symbol: class SamePackage location: class Testp1 6 errors
package p1;
public class Testp1
{
public static void main(String a[])
{
Protection ob = new Protection();
Derived ob1 = new Derived();
SamePackage ob2 = new SamePackage();
}
}
package p1;
public class Protection
{
int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection()
{
System.out.println("Inside base constructor.");
System.out.println(" n = "+n);
System.out.println("n_pri = "+n_pri);
System.out.println("n_pro = "+n_pro);
System.out.println("n_pub = "+n_pub);
}
}
package p1;
class Derived extends Protection
{
Derived()
{
System.out.println("Inside Derived constructor.");
System.out.println(" n = "+n);
// System.out.println("n_pri = "+n_pri);
System.out.println("n_pro = "+n_pro);
System.out.println("n_pub = "+n_pub);
}
}
package p1;
class SamePackage{
SamePackage(){
Protection p = new Protection();
System.out.println("Inside SamePackage constructor.");
System.out.println(" n = "+p.n);
// System.out.println("n_pri = "+p.n_pri);
System.out.println("n_pro = "+p.n_pro);
System.out.println("n_pub = "+p.n_pub);
}
}
答案 0 :(得分:1)
当你有包时,你不能像在没有包的类中那样简单地编译或运行。
编译时,您需要导航到包文件夹之外,然后使用命令javac [package]/[class]
进行编译。在您的情况下,它应该是
javac p1/Testp1.java
并且在运行时使用此命令java[package.class]
..所以在你的情况下它应该是
java p1.Testp1
确保你不在包[p1]里面,你应该在包之外[编译后通过cmd导航到文件夹learn_java]。
最后这就是你的cmd的样子
C:\Users\jaina_000\Desktop\learn_java>javac p1/Testp1.java C:\Users\jaina_000\Desktop\learn_java>java p1.Testp1 Inside base constructor. n = 1 n_pri = 2 n_pro = 3 n_pub = 4 Inside base constructor. n = 1 n_pri = 2 n_pro = 3 n_pub = 4 Inside Derived constructor. n = 1 n_pro = 3 n_pub = 4 Inside base constructor. n = 1 n_pri = 2 n_pro = 3 n_pub = 4 Inside SamePackage constructor. n = 1 n_pro = 3 n_pub = 4 C:\Users\jaina_000\Desktop\learn_java>