【ThinkingInJava】9、继承与清理
/** * 书本:《Thinking In Java》 * 功能:继承与清理 * 文件:Frog.java * 时间:2015年4月1日19:38:22 * 作者:cutter_point */ package Lesson8Polymorphism; import static net.mindview.util.Print.*; class Characteristic { private String s; Characteristic(String s) { this.s = s; print("Creating Characteristic " + s); } protected void dispose() { print("disposing Characteristic " + s); } } class Description { private String s; Description(String s) { this.s = s; print("Creating Description " + s); } protected void dispose() { print("disposing Description " + s); } } //类的组合 class LivingCreature { private Characteristic p = new Characteristic("is alive"); private Description t = new Description("Basic Living Creature"); LivingCreature() { print("LivingCreature()+构造函数"); } protected void dispose() { print("LivingCreature dispose"); t.dispose(); p.dispose(); } } //类的继承 class Animal extends LivingCreature { private Characteristic p = new Characteristic("has heart"); private Description t =new Description("Animal not Vegetable"); Animal() { print("Animal()"); } protected void dispose() { print("Animal dispose"); t.dispose(); p.dispose(); super.dispose(); } } class Amphibian extends Animal { private Characteristic p = new Characteristic("Can live in water"); private Description t = new Description("Both water and land"); Amphibian() { print("Amphibian()"); } protected void dispose() { print("Amphibian dispose"); t.dispose(); p.dispose(); super.dispose(); } } public class Frog extends Amphibian { private Characteristic p = new Characteristic("Croaks"); private Description t = new Description("Eats bugs"); public Frog() { print("Frog()"); } protected void dispose() { print("Frog dispose"); t.dispose(); p.dispose(); super.dispose(); } public static void main(String args[]) { Frog frog = new Frog(); print("Bye bye!"); frog.dispose(); print("all is over"); } }
* 终结:
* 1、首先就是调用父类的构造函数
* 2、到根父类之后,首先实例化数据成员(一般是类的组合的实现)
* 3、数据成员实例化之后,再是构造函数里面的类容
输出:
Creating Characteristic is alive obj1
Creating Description Basic Living Creature obj1
LivingCreature()+构造函数 obj1
Creating Characteristic has heart obj1
Creating Description Animal not Vegetable obj1
Animal() obj1
Creating Characteristic Can live in water obj1
Creating Description Both water and land obj1
Amphibian() obj1
Creating Characteristic Croaks obj1
Creating Description Eats bugs obj1
Frog() obj1
Bye bye! obj1
Frog dispose obj1
disposing Description Eats bugs obj1
disposing Characteristic Croaks obj1
Amphibian dispose obj1
disposing Description Both water and land obj1
disposing Characteristic Can live in water obj1
Animal dispose obj1
disposing Description Animal not Vegetable obj1
disposing Characteristic has heart obj1
LivingCreature dispose obj1
disposing Description Basic Living Creature obj1
disposing Characteristic is alive obj1
all is over obj1
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。