关于继承的一点理解

关于继承,把握一点,子类继承父类:

  1. 其实继承了父类所有的属性和方法,只不过有些属性和方法因为权限的问题,没办法直接调用拿到只能通过调用父类的相关方法间接的拿到自己从父类那里继承到的属性和方法。

示例代码:

package com.ethan;

public class Demo {
    public static void main(String[] args) {
        Phone phone = new Phone("xiaomi","200",3699.0);
        Phone phone2 = new Phone("huawei","100",6699.0);

        Father father = new Father();
        father.init(phone);
        String phoneBrandName1 = father.getPhoneBrandName();
        System.out.println(phoneBrandName1);
        Son son = new Son();
        son.init(phone2);
        son.playPhone();

    }

}

/**
 * 父类中的private的phone属性,其实子类仍然是继承了该属性!!!
 * 但是子类没办法直接访问,无法直接得到phone的值。
 * 只能间接访问:!!!
 * 如下所示就是playPhone()方法通过调用父类的getPhoneBrandName()方法,获取son对象中phone的值,你会发现
 * 获取到的phone仍然是子类自己的phone的值,但是你如果直接获取又获取不到,权限不足。
 *
 */
class Son extends Father{

   /*
    @Override
    public void init(Phone phone) {
        System.out.println("son init!"+phone);
    }
    */

    public void playPhone(){

        String phoneBrandName = getPhoneBrandName();
        System.out.println(phoneBrandName);
    }
}



class Father{
    private Phone phone;

    public void init(Phone phone){

        this.phone = phone;

        System.out.println("father init!"+phone);
    }

    public String getPhoneBrandName(){
        return phone.getBrandName();
    }
}


class Phone{
    private String brandName;
    private String phoneSize;
    private Double price;

    public Phone(String brandName, String phoneSize, Double price) {
        this.brandName = brandName;
        this.phoneSize = phoneSize;
        this.price = price;
    }

    public Phone() {
    }

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getPhoneSize() {
        return phoneSize;
    }

    public void setPhoneSize(String phoneSize) {
        this.phoneSize = phoneSize;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Phone{" +
                "brandName='" + brandName + '\'' +
                ", phoneSize='" + phoneSize + '\'' +
                ", price=" + price +
                '}';
    }
}

posted @ 2022-01-10 00:14  ethanSung  阅读(37)  评论(0编辑  收藏  举报