Java:对象中的数组属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21006061/
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
Java: array attribute in object
提问by maximilliano
I am a newbie in Java programming and was just wondering if you can do this: I have a object class Person:
我是 Java 编程的新手,只是想知道您是否可以这样做:我有一个对象类 Person:
public class Person {
public String name;
public String[] friends;
}
If yes how to initialse it, i.e.
如果是,如何初始化它,即
newPerson.name = "Max";
newPerson.friends = {"Tom", "Mike"};
I tried to do it like that, but it does not work.
我试图这样做,但它不起作用。
采纳答案by Ashish
try this
尝试这个
new Person("Max", new String[]{"Tom", "Mike"});
You would also need a constructor to initialize the variables.
您还需要一个构造函数来初始化变量。
public Person(String name, String[] friends){
this.name = name;
this.friends = friends;
}
As a good practice, you should also limit the access level of variables in your class to be private. (unless there is a very good reason to make them public.)
作为一种好的做法,您还应该将类中变量的访问级别限制为私有。(除非有充分的理由将它们公开。)
回答by Eugen Halca
try
尝试
newPerson.friends = new String[]{"Tom", "Mike"}
newPerson.friends = new String[]{"Tom", "Mike"}
回答by Elliott Frisch
You can do it like this
你可以这样做
public static class Person {
public String name;
public String[] friends;
}
public static void main(String[] args) {
Person newPerson = new Person();
newPerson.name = "Max";
newPerson.friends = new String[] {"Tom", "Mike"};
}
回答by Inverce
Thats actually pretty simple
这其实很简单
U can initialize in creation (thats the easiest method):
你可以在创建中初始化(这是最简单的方法):
public class Person {
public String name = "Max";
public String[] friends = {"Adam","Eve"};
}
U could initialize variables in your constructor
你可以在你的构造函数中初始化变量
public class Person {
public String name;
public String[] friends;
public Person(){
name = "Max";
friends = new String[] {"Adam", "Eve"};
}
}