AP计算机教程9-7:访问继承的private field
继承意味着child class自动包含有parent class中定义的field和method。但如果继承的field是private
的,child class则不能直接访问它们,需要通过parent class中所提供的一些public
method(术语叫做getter或accessor)来读取它们,以及另一些public
method(术语叫做setter或mutator)来操作它们。
例如,如果parent中有一个名为name
的private
field,则一般也会提供如下所示的getName
和setName
这两个public
method。在setName
中,先检查传入的字符串参数是否为null
,然后再进行更新操作并返回是否成功。class Employee
继承了name
,但是需要通过getName
和setName
来操作它。
class Person { private String name; public String getName() { return name; } public boolean setName(String theNewName) { if (theNewName != null) { this.name = theNewName; return true; } return false; } } public class Employee extends Person { private static int nextId = 1; private int id; public Employee() { id = nextId; nextId++; } public int getId() { return id; } public static void main(String[] args) { Employee emp = new Employee(); emp.setName("Mark"); System.out.println(emp.getName()); System.out.println(emp.getId()); } }
0:00
Given the following class definitions which of the following would not compile if it was used in place of the missing code in the main method?
class Item { private int x; public void setX(int theX) { x = theX; } // ... other methods not shown } public class EnhancedItem extends Item { private int y; public void setY(int theY) { y = theY; } // ... other methods not shown public static void main(String[] args) { EnhancedItem currItem = new EnhancedItem(); // missing code } }
EnhancedItem
无法直接访问继承的x
,注意因为main
method在EnhancedItem
内,还是能直接访问y
的。3
0 条评论