3

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.

Jason
  • 11,263
  • 21
  • 87
  • 181
maximilliano
  • 163
  • 1
  • 2
  • 16

4 Answers4

10

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.)

Ashish
  • 1,121
  • 2
  • 15
  • 25
1

try

newPerson.friends = new String[]{"Tom", "Mike"}

Eugen Halca
  • 1,775
  • 2
  • 13
  • 26
1

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"};
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

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"};
      }
 }
Inverce
  • 1,487
  • 13
  • 27