K
K
kvaks2019-11-15 16:19:05
Java
kvaks, 2019-11-15 16:19:05

Same values ​​in array of objects?

There is a Human class

public class Human {
    public static String name;

    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }

In Main I connect it, when displaying all the values ​​from it are the same, as in the last object.
public class Main {

       public static void main(String[] args) {
            Human humans[] = new Human[4];

           humans[0].setName("zzz");
           humans[1].setName("xxx");
           humans[2].setName("qqq");
           humans[3].setName("www");

System.out.println(humans[1].getName());

Tell me what am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
protven, 2019-11-15
@protven

Generally the code of a curve, really NPE will be. if you rewrite it to normal it won't work as you expect because the name field is static. Learn the basics. static means the value is the same for all instances.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question