Search code examples
javaarraysobjectinstance-variables

Why i cant reach instance of object in object array?


I'm starting to learn java, and faced this problem when I can reach object name and lastName, but can't reach if I put them in object array.

public class Human {
    String name;
    String lastName;
    String[] people;

    People(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    };

    public static People tom = new People("Tom", "Tommy");
    public static People ted = new People("Ted", "Teddy");

    public static Object[] objects = {
            tom,
            ted
    };
    public static void main(String[] args) {
        System.out.println(tom.lastName);
        System.out.println(objects[0]);

and this line I need does not work.

        System.out.println(objects[0].lastName); 
}

Solution

  • Simple: you declared that array of type Object.

    Objects don't have names, only an instance of People has!

    In other words: you want to declare an array of People, not Object.

    You see, the compiler only "remembers" the type that is used on the left hand side of that variable declaration. It does not know that you in fact created an array of Object and placed solely instances of People inside that array.

    And unrelated: people implies plural. You should rather call that class Person, or maybe PersonInfo.