本帖最后由 嘿~~ 于 2014-8-11 15:24 编辑
将父类的成员变量私有化,子类不能通过对象来直接获取,子类构造函数可以通过super来指定调用父类的构造函数来完成初始化- class ExtendsDemo
- {
- public static void main(String[] args)
- {
- Fu z = new Zi("zhangsan",19,"sc0012");
-
- //子类对象不能直接访问父类被私有化的成员变量
- //System.out.println(z.name+"----"+z.age);
- }
- }
- class Fu
- {
- //将父类的属性私有化,子类不能直接获取
- private String name ;
- private int age;
- Fu(){
- System.out.println("Fu类空参数构造函数");
- }
- Fu(String name,int age){
- this.name = name;
- this.age = age;
- System.out.println("Fu类带参数构造函数");
- }
- }
- class Zi extends Fu
- {
- private String schoolCode ;
- Zi(String name,int age,String schoolCode){
- //通过super来指定调用父类对应的构造函数
- super(name,age);
- this.schoolCode = schoolCode;
- //创建子类对象时,子类获得了属性
- System.out.println(name+"----"+age+"----"+schoolCode);
- }
- }
复制代码 |
|