[英]Using main class inside the package in java
I am trying to to run the file Demo.java which is calling Protection class within the same package but it is giving error This is the main class.我试图运行在同一个包中调用保护类的文件 Demo.java,但它给出了错误这是主类。
package p1;
// Instantiate the various classes in p1.
class Demo {
public static void main(String args[]) {
Protection ob1 = new Protection();
//Derived ob2 = new Derived();
//SamePackage ob3 = new SamePackage();
}
}
And this is the class that I want to use in the main class.这是我想在主类中使用的类。
package p1;
public class Protection {
public int n = 1;
private int n_pri = 2;
protected int n_pro = 3;
public int n_pub = 4;
public Protection() {
System.out.println("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);
}
}
It is giving this error:它给出了这个错误:
$ javac Demo.java
Demo.java:6: error: cannot find symbol
Protection ob1 = new Protection();
^
symbol: class Protection
location: class Demo
Demo.java:6: error: cannot find symbol
Protection ob1 = new Protection();
^
symbol: class Protection
location: class Demo
2 errors
error: compilation failed
javac
, not java
onlyjavac
,而不仅仅是java
When you use the command java
, you can execute a file, but only the classes in that file.当您使用命令
java
,您可以执行一个文件,但只能执行该文件中的类。 Here you have several files, so you should compile them in order to use them.这里有几个文件,所以你应该编译它们以便使用它们。
Do the following:请执行下列操作:
$ mkdir p1
$ mv Demo.java Protection.java p1/
# edit p1/Demo.java to change `class Demo` to `public class Demo`
$ javac p1/*
$ java p1.Demo
This worked and resulted in the following:这有效并导致以下结果:
base constructor
n = 1
n_pri = 2
n_pro = 3
n_pub = 4
You could try this:你可以试试这个:
javac .\\Demo.java .\\Protection.java
;javac .\\Demo.java .\\Protection.java
; then you can see two .class files generatedcd ..
, then you can see your package p1
cd ..
,然后你可以看到你的包p1
java p1.Demo
then you can see the expected outputjava p1.Demo
然后你可以看到预期的输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.