Java 中继承时的访问特点

继承后成员的访问特点

父类的构造方法不能被继承

父类的私有成员

父类的私有成员可以被子类继承,但子类不能直接访问,需要借助父类的公有方法

class Father {
    private String fatherName;

    public Father() {

    }

    public Father(String fatherName) {
        this.fatherName = fatherName;
    }

    public String getFatherName() {
        return fatherName;
    }

    public void setFatherName(String fatherName) {
        this.fatherName = fatherName;
    }

    private void printFatherName() {
        System.out.println("father name: " + fatherName);
    }

    public void publicMethod() {
        printFatherName();
    }
}

class Son extends Father{
    public void sonMethod() {
        /**
         * 2. 私有变量或私有方法
         *         1. 子类可以继承父类的私有变量,但不能直接访问,需要使用父类的 setter/getter
         */
        // System.out.println(fatherName); // 会编译异常
        String fatherName = getFatherName(); // 可以拿到 fatername
        System.out.println(fatherName); 

        // printFatherName(); // 编译异常
        publicMethod(); // 可以正常打印 father name: xxx
    }
}

父类的公有变量

子类可以继承父类的公有变量并直接访问

this 和 super

this

  1. 访问本类的构造方法,根据实参推定访问的是哪一个
  2. 访问本类的成员

注意
3. this() 只能在构造函数内第一行被使用

class Father {
    private String name;

    public Father() {
        System.out.println("无参构造");
    }

    public Father(String name) {
        // 访问构造函数,创建时会打印 "无参构造"
        this();
        this.name = name;
        // this(); // this() 必须被放在第一行,编译异常
    }

    public String getName() {

        // this(); // this(), 只能在构造方法内被使用,编译异常
        return name;
    }

    public void setName(String name) {
        // this.成员:用来访问本类的成员
        this.name = name;
    }

    private void cook() {
        System.out.println("father is cooking...");
    }

    public void print() {
        // this.成员:用来访问本类的成员
        this.cook();
    }
}

super

  1. super() :访问父类的构造方法
  2. 访问父类的公有成员

注意
3. super() 必须在构造方法的第一行(也就是 thissuper 无法在同一个 constructor 中调用)
4. 子类的构造方法会默认调用 super(),如果此时父类没有无参构造方法,那么会编译异常

class Son extends Father{
    public Son() {
        super();
        System.out.println("son 无参构造");
        // super(); // 编译异常:必须在第一行
    }
    
    public void sonMethod() {
        // super(); // 编译异常:必须在 constructor 内调用
        // super.name; //编译异常: private 访问不了 
        String fatherName = super.getName(); // 
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值