3

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

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Assume you have a bus for people... makes a lot of difference between this and mine :)
@davidxxx Well. SO is more on the hobby side of things. After I wrote those answers, I went to clean up some old farmer house, filled a whole container with the trash bags that my spouse "prepared" during the week. That was work ;-)
@GhostCat I joked of course :) That is indeed "work" but by applying OOP and design patterns, I bet it was a simple formality for you ! Cheater ! ;-p
3

You can explicitly cast the object and change

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

as:

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

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.