Java: array attribute in object

26,879

Solution 1

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

Solution 2

try

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

Solution 3

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"};
}

Solution 4

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"};
      }
 }
Share:
26,879
maximilliano
Author by

maximilliano

Updated on January 09, 2020

Comments

  • maximilliano
    maximilliano over 4 years

    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.

  • Sergey Kalinichenko
    Sergey Kalinichenko over 10 years
    +1 for suggesting a constructor. You may want to mention that making fields public is not a good practice.
  • Ashish
    Ashish over 10 years