java 使用多个类java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5688474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using multiple classes java
提问by Jeel Shah
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.
我想知道如何在 Java 中使用多个类。我知道如何使用其他类的方法以及构造函数,但我想知道如何创建一个新的“对象”。如果我正在制作一个 PersonDirectory,那么我可以拥有一个名为 Person 的类,它具有 Name 和 Age 属性。然后我想在我的 PersonDirectory 类中创建一个 Person[] 并为其添加姓名和年龄。我怎样才能做到这一点?我有一些我做过的代码,但它似乎不起作用。
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;
}
}
回答by Petar Minchev
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.
这是因为Person
类中的属性是静态的。静态意味着它们在所有对象(实例)之间共享。从Person
类中删除 static 关键字,你会没事的。