/**
*Exercise 17: (1) Modify Exercise 16 so that Frog overrides
*the method definitions from the base class (provides new definitions
*using the same method signatures). Note what happens in main( ).
*
* 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(int i){
System.out.println("Amphibian都冬眠");
}
//因为有了构造函数, 所以下面可以用Amphibian类型的变量了
static void wakeUp(Amphibian x){
x.doHibernate(6);
System.out.println("春天来了, 该醒醒了!");
}
}
public class Frog extends Amphibian{
@Override void doHibernate(int i){
System.out.println("作为两栖动物的青蛙要冬眠");
}
public static void main(String[] args) {
Frog y=new Frog();
//注意下面有个upcast, y是frog, 但在wakeUp中,
//被自动upcast成了wakeUp能够接受的amphibian类型,
//因为frog is an amphibian, 所以可以在wakeUp()中使用
Amphibian.wakeUp(y);
}
}
/**
* output:
* 作为两栖动物的青蛙要冬眠
* 春天来了, 该醒醒了!
*/
//注意, 在wakeUp(y)中, 虽然有upcast, 但是,
//y.doHibernate仍然用的是Frog类的doHibernate方法,
//而不是Amphibian类的doHibernate方法
182页习题17
最新推荐文章于 2024-04-28 03:10:34 发布