3

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;
 }
}
Bala R
109k23 gold badges203 silver badges212 bronze badges
asked Apr 16, 2011 at 18:04
1
  • 1
    what 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? Commented Apr 16, 2011 at 18:08

1 Answer 1

7

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.

answered Apr 16, 2011 at 18:06

3 Comments

when print out Person[0] it give me something very odd.
never mind. Thanks, i also noticed you needed to get rid of private.
@user681159: There is no reason to remove any private from the code in the question.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.