开发者

How do i use a class from a different file in java?

Am new at Java and this is what am attempting to do;

I Have two files located on this folder on a windows machine;

d:\programs\sims\javasim\src\com\jsim\
Person.java
Building.java

On my Building.java am making use of class Person located in file Person.java i.e.

package com.jsim;
ArrayList<Person> personList = new ArrayList<Person>();

Am compiling the files from this folder

d:\programs\sims\javasim\src

But when i try to compile Building.Java, the compiler tells me

d:\programs\sims\src\javac com/jsim/Building.java

com\jsim开发者_如何学C\Building.java:10: cannot find symbol
symbol  : class Person
location: class com.jsim.Building
        private ArrayList<Person>personList = new ArrayList<Person>();
                          ^

How can i make Building.java know about class Person in file Person.java?

Gath


execute javac *.java or javac Person.java Building.java or javac Building.java Person.java to compile your classes.

Seems like Person.java is not compiled before compiling Building.java file.

Building needs Person's class file for compiling instead of .java file.


You need to get your package names and imports to be consistent. The information you posted contains two different package names, so you either need to put the classes in the same package or add an import statement.


You must import the class you're referencing:

import Person;


I think the problem is indeed with this like:

private ArrayList<Person>personList = new ArrayList<com.liftsim.Person>();

Since the class you are writing is in the same package as the others (com.jsim) you don't need to import anything. However, you have specified a totally different class name in your initialisation it seems (I'm guessing using the Eclipse autocomplete?) -- so simply remove all the imports and re-write the above line as follows:

private ArrayList<Person>personList = new ArrayList<Person>();


I discovered that when I am using Eclipse, I can't use -non-public- classes inside other files in the same package. Note that I am using the default package while this happens. This behavior changes when I open both files and have two windows open in the editor. In that case, I CAN use classes in other files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜