QuestionQ142

Working with Inheritance

Given the contents of the Tree.java and Plant.java files:

Question Image

and this code fragment:

Question Image

Which code fragment is valid on line 10?

  • A t.m1();
  • B t.m1();t.m3();
  • C t.m1();t.m2();t.m3();t.m4();
  • D t.m1();t.m3();t.m4();
Explanation

m1() is public, so it is accessible through a Tree reference. m2() is private, and m4() has package-private access, so neither is accessible from Plant in the different branch package. m3() is protected, but outside Tree’s package a subclass may access it only through a reference whose type is the subclass or one of its subclasses; t is declared as Tree, so t.m3() is invalid. Oracle’s Java Language Specification §6.6.2.1 defines this protected-access restriction.

Learn more

Community Discussion

No comments yet. Be the first to start the discussion!