开发者

Using multiple classes java

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 nam开发者_运维问答e = 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;
    }

}


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜