nerdexam
Oracle

1Z0-809 · Question #148

Given the following classes: public class Employee { public int salary; } public class Manager extends Employee { public int budget; } public class Director extends Manager { public int…

The correct answer is A. manager .stockoption = 500. A and D are the two options that fail to compile, because they attempt to access fields that don't exist on the declared type of the variable. A fails: manager is declared as type Manager, and Manager only inherits salary from Employee and defines budget - stockoptions belongs…

Question

Given the following classes: public class Employee { public int salary; } public class Manager extends Employee { public int budget; } public class Director extends Manager { public int stockoptions; } And given the following main method: public static void main(String[] args) { Employee employee = new Employee(); Manager manager = new Manager(); Director director = new Director(); //line n1 } Which two options fail to compile when placed at line n1 of the main method?

Options

  • Amanager .stockoption = 500;
  • Bdirector .stockoption = 1_000;
  • Cdirector .salary = 50_000;
  • Demployee .budget = 200_000;
  • Eemployee .salary = 50_000;
  • Fmanager .budget = 1_000_000;

How the community answered

(21 responses)
  • A
    71% (15)
  • C
    10% (2)
  • E
    14% (3)
  • F
    5% (1)

Explanation

A and D are the two options that fail to compile, because they attempt to access fields that don't exist on the declared type of the variable.

  • A fails: manager is declared as type Manager, and Manager only inherits salary from Employee and defines budget - stockoptions belongs to Director (a subclass), and a parent type cannot access a child's members.
  • D fails: employee is declared as type Employee, which only has salary - budget is defined in Manager (a subclass), so it's inaccessible via an Employee reference.
  • B passes: director is declared as Director, which does define stockoptions - valid access.
  • C passes: director inherits salary all the way up from Employee - subclasses inherit all non-private members.
  • E passes: employee.salary directly accesses its own field.
  • F passes: manager.budget accesses Manager's own field.

Memory tip: Inheritance flows down - a variable can only see fields at its own level and above (ancestors), never below (descendants). Think of it as "a Manager knows about Employee things, but not Director things."

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice