I would like to know how to use multiples clas in Java. I know how use method from other class and also constructors but i would like know how create a new "object" for example. If i am making a PersonDirectory, then i can have class called Person which has the attributes Name and Age. Then i want to make a Person[] in my PersonDirectory Class and add names and ages to it. How can i do that? I have some code that i did, but it doesn't seem to work out.
import java.io.*;
public class PersonDirectory {
static BufferedReader br = new BufferedReader
(new InputStreamReader(System.in));
static Person[] personArray = new Person[2];
public static void main(String[] args) throws IOException{
for (int i = 0; i < personArray.length; i++) {
System.out.print("Please enter the name of the person: ");
String name = br.readLine();
System.out.print("Please enter the age of the person: ");
int age = Integer.parseInt(br.readLine());
personArray[i] = new Person(name,age);
}
for(Person p : personArray) {
System.out.println("The name is "+p.getName()+" and the age is "+p.getAge());
}
}
}
second class
public class Person {
private static String name = "";
private static int age = 0;
public Person(String name,int age) {
this.name = name;
this.age = age;
}
public static String getName() {
return name;
}
public static int getAge() {
return age;
}
}
-
1what do you mean it doesnt seem to work, what is going wrong, does it compile ok? are you getting errors/warnings, if so what are they?Eamonn McEvoy– Eamonn McEvoy2011年04月16日 18:08:20 +00:00Commented Apr 16, 2011 at 18:08
1 Answer 1
This is because the properties in the Person
class are static. Static means that they are shared between all object(instances). Remove the static keyword from the Person
class and you will be fine.
3 Comments
private
from the code in the question.