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";
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With