高级农民
- 积分
- 1752
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-3-18
- 最后登录
- 1970-1-1
|
本帖最后由 HNAKXR 于 2016-2-6 20:43 编辑
1 Creating Cats
Animal Kitty says: MEOW!
Animal Garfield says: Meow!
2 Raining Cats and Dogs- public class TestAnimals {
- public static void main(String[] args) {
- Animal a = new Animal("Pluto", 10);
- Cat c = new Cat("Garfield", 6);
- Dog d = new Dog("Fido", 4);
- a.greet(); // Animal Pluto says: Huh?
- c.greet(); // Cat Garfield says: Meow!
- d.greet(); // Dog Fido says: WOOF!
- a = c;
- a.greet(); // Cat Garfield says: Meow!
- ((Cat) a).greet(); // Cat Garfield says: Meow!
- /* Compiler error!
- * because a Dog is an Animal, but an Animal is not necessarily a Dog. */
- // a = new Dog("Hiernoymus", 10);
- // d = a;
- /* We have to make an awkward cast. */
- a = new Dog("Hiernoymus", 10);
- d = (Dog) a;
- }
- }
复制代码 3 An Exercise in Inheritance Misery- class C extends B {
- public int y = x + 1;
- public void m2() {System.out.println("Cm2-> " + super.x);}
- // public void m3() {System.out.println("Cm3-> " + super.super.x);} // super.super.x is not allowed!
- public void m4() {System.out.println("Cm4-> " + y);}
- // public void m5() {System.out.println("Cm5-> " + super.y);} // there is no variable y in superclass B.
- }
复制代码- class D {
- public static void main (String[] args) {
- // B a0 = new A(); // A can't be converted to B. Must cast if you want.
- // a0.m1(); // see the line above.
- A b0 = new B();
- System.out.println(b0.x);
- b0.m1(); // class B hides a field in class A.
- b0.m2(); // you should never hide fields.
- // b0.m3(); // as you’ll see, it’s confusing! see C.java: super.super.x not allowed!
- B b1 = new B();
- b1.m3();
- b1.m4();
- A c0 = new C();
- c0.m1();
- // C c1 = (A) new C(); // B can't be converted to C. Must cast if you want.
- A a1 = (A) c0;
- C c2 = (C) a1;
- c2.m4();
- // c2.m5(); // see C.java: there is no variable y in superclass B.
- // ((C) c0).m3(); // very tricky! see C.java: super.super.x not allowed!
- // (C) c0.m3(); // same as the line above.
- b0.update();
- b0.m1();
- b0.m2();
- }
- }
复制代码5
Am1-> 5
Bm2-> 10
Bm3-> 5
Bm4-> Am2-> 5
Am1-> 5
Cm4-> 11
Am1-> 99
Bm2-> 10
|
|