Jam
Jam

Reputation: 49

Basic java inheritance/arrays. How to use subclass variables with arrays

In this main method:

package practice;

public class PersonTest {

    public static void main(String[] args)
    {
        Person[] people = new Person[2];

        people[0] = new Person();
        people[1] = new Employee();

        System.out.println(people[1].job);
    }
}

I get a compiler error when I try to use job. Can anyone tell me why, and how it's supposed to be done? Below are the classes I created for the above method:

The Person class:

package practice;

public class Person{
    String name;
    int age;
    public Person () {
        this.name = "undefined";
        this.age = 0;
    }
}

And the Employee class:

package practice;

public class Employee extends Person{
    String job;
    Employee () {
        super();
        this.job = "job";
    }
}

Upvotes: 3

Views: 95

Answers (4)

Jam
Jam

Reputation: 49

Thank you everyone. That answers my question. I think the fact that you don't have to cast to methods like that was throwing me.

Upvotes: 0

GhostCat
GhostCat

Reputation: 140457

Simple: because the compile time knowledge about that array is: it is an array of Person objects.

Person[] people = new Person[2];

The compiler doesn't care that you decided to put an Employee object into one of the array slots.

It is perfectly fine to put Person and Employee objects in such arrays - but when you need Employee specific things, you would do something like:

if (people[i] instanceof Employee) {
 System.out.println( ( (Employee) people[i] ). job)

Assume you have a bus for people. Your idea is that anybody sitting in that bus is an employee. Nope - it is a bus of people - you don't know about the individuals sitting there - until you ask them about their nature.

Upvotes: 5

nagendra547
nagendra547

Reputation: 6302

job is member variable of Employee Class not of Person. So you need to cast explicitly into Employee to access it.

((Employee) people[1]).job

Upvotes: 1

Naman
Naman

Reputation: 31888

You can explicitly cast the object and change

System.out.println(people[1].job);

as:

System.out.println(((Employee) people[1]).job);

Upvotes: 3

Related Questions