Reputation: 163
I am a newbie in Java programming and was just wondering if you can do this: I have a object class 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.
Upvotes: 3
Views: 36400
Reputation: 1121
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.)
Upvotes: 10
Reputation: 1496
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"};
}
}
Upvotes: 1
Reputation: 201487
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"};
}
Upvotes: 1