编译包含其他类型对象的java类时收到错误消息

时间:2012-11-20 12:21:52

标签: java

我是java编程语言的新手。我做了一个包名包。其中包含两个java类A.java和B.java。我正在使用jdk1.5和tomcat。我想创建一个A类型的对象并将其放在B.java中。以下是我尝试这样做但收到两条错误消息的方法。

包装;

A.java

public class A {

        private String str;

    public A(){} //constructor method
    public void setName(String str){
        this.str = str;
    }
    public String getName(){
        return str;
    }
}

B.java

public class B {

        private String temp;

    public B(){} //constructor method

    public String getTemp(){
        A a = new A();      //creating an object of A type
        temp = a.getName();  //assigning the value of getName method to temp variable
        return temp;        // returning temp variable  
    }
}

Jdk1.5,tomcat和package pack在以下目录中

d:\ Java和GT;

以下是我为编译A.java和B.java而采取的步骤

编译A.java

D:\>cd java
D:\Java>cd pack
D:\Java\pack>set path=D:\java\jdk1.5\bin  (**setting up path of jdk1.5**)
D:\Java\pack>javac A.java (**Compiling A.java. Compiled it successfully**)

编译B.java

D:\Java\pack>javac A.java (**Compiling B.java. Unable to compile**)

**(Error Message is below)**

D:\Java\pack>javac B.java
B.java:9: cannot find symbol
symbol  : class A
location: class pack.B
                A a = new A();      //creating an object of A type
                ^
B.java:9: cannot find symbol
symbol  : class A
location: class pack.B
                A a = new A();      //creating an object of A type
                          ^
2 errors

2 个答案:

答案 0 :(得分:1)

不是从目录D:\Java\pack编译类,而是转到包的基本目录D:\Java,然后从那里编译并运行:

D:\Java> javac pack\A.java
D:\Java> javac pack\B.java

确保设置CLASSPATH环境变量,或使用-cp选项指定类路径:

D:\Java> javac -cp . pack\A.java
D:\Java> javac -cp . pack\B.java

(注意:-cp .表示您在类路径中包含当前目录,由.表示。)

答案 1 :(得分:0)

确保A类和B类都有一个包语句

A.java

package pack;
public class A{
....
}

B.java

package pack;
public class B{
...
}