/**
* Exercise 16: (2) Create a class called Amphibian.
* From this, inherit a class called Frog. Put appropriate methods in the base class.
* In main( ), create a Frog and upcast it to Amphibian
* and demonstrate that all the methods still work.
*/
package reusing;
class Amphibian{
Amphibian(){}
void doHibernate(){
System.out.println("Amphibian都冬眠");
}
//因为有了构造函数, 所以下面可以用Amphibian类型的变量了
static void wakeUp(Amphibian x){
x.doHibernate();
System.out.println("春天来了, 该醒醒了!");
}
}
public class Frog extends Amphibian{
public static void main(String[] args) {
Frog y=new Frog();
//注意下面有个upcast, y是frog, 但在wakeUp中,
//被自动upcast成了amphibian,
//因为frog is an amphibian, 所以可以在wakeUp()中使用
Amphibian.wakeUp(y);
}
}
//output:
//Amphibian都冬眠
//春天来了, 该醒醒了!
182页习题16
最新推荐文章于 2024-07-15 16:04:11 发布