简体   繁体   中英

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 ie

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\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

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.

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.

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.

您必须导入您引用的类:

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>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM