哈利路亚
Let's take one million years picnic
欢迎来到Sean Cleveland的博客
JAVA学习日报 7.17

在欺负去年C++课程中实验2的继承派生问题前,我认为该仔细研究一下JAVA里的继承原则

在这里简单地写了一个继承关系(dessert指甜点;Macaron指马卡龙)

class Dessert{
    public String[] teast= {"egg","Cake Flour"};
    private String steast= "suger";
}
class Macaron extends Dessert{
    public String[] extra={"milk","almond powder"};
    private String sextra="colorlip";
    public void cookbook(){
        System.out.print(teast+"\n"+steast+"\n");
    }
}

这里编译器报错,错误内容如下:

字段Dessert.steast不可见

那么这里我们就可以知道,和C++相同,子类确实可以访问父类的公有成员,但不能访问其私有成员

我们再派生一个抹茶马卡龙(Matcharon)类:

class Matcharon extends Macaron{
    String[] nextextra= {"Matcha","tea leaf"};
    public void cookbook3(){
        System.out.print(teast[0]+" "+teast[1]+"\n");
        System.out.print(nextextra[0]+" "+nextextra[1]+"\n");
    }

没有报错,所以JAVA里的继承关系完全是可传递的

最终程序代码如下:

package test;
class Dessert{
    public String[] teast= {"egg","Cake Flour"};
    private String steast= "suger";
    public void cookbook1(){
        System.out.print(steast+"\n");
    }
}
class Macaron extends Dessert{
    public String[] extra={"milk","almond powder"};
    private String sextra="colorlip";
    public void cookbook2(){
        System.out.print(teast[0]+" "+teast[1]+"\n");
        System.out.print(sextra+"\n");
    }
}
class Matcharon extends Macaron{
    String[] nextextra= {"Matcha","tea leaf"};
    public void cookbook3(){
        System.out.print(teast[0]+" "+teast[1]+"\n");
        System.out.print(nextextra[0]+" "+nextextra[1]+"\n");
    }
}

public class test1 {

    public static void main(String[] args) {
        Matcharon o=new Matcharon();
        o.cookbook1();
        o.cookbook2();
        o.cookbook3();
    }

}

运行结果为:

 

 期待明天摧残老作业(笑)

posted on 2020-07-17 18:14  哈利路亚#0207  阅读(132)  评论(0编辑  收藏  举报
Live2D