2018 cs61b dis4
2022/5/25 23:24:00
本文主要是介绍2018 cs61b dis4,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
https://sp18.datastructur.es/materials/discussion/disc04.pdf
public class Animal{ protected String name, noise; protected int age; public Animal(String name, int age){ this.name = name; this.age = age; this.noise = "Huh?"; } public String makeNoise(){ if (age < 5) { return noise.toUpperCase(); } else{ return noise; } } public void greet(){ System.out.println("Animal " + name + " says: " + makeNoise()); } } public class Cat extends Animal{ public Cat(String name){ this.name = name; this.noise = "Meow!" } @Override public void greet(){ System.out.println("Cat " + name + " says: " + makeNoise()); } } /** (A) Animal Pluto says: Huh? (B) Cat Garfield says: Meow! (C) Dof Fido says: WOOF! (D) Cat Garfield says: Meow! (E) Cat Garfield says: Meow! //a是一个Animal类,而d是一个Dog,不是直接赋值,需要进行一个强制转换。 */ class A { public int x = 5; public void m1() {System.out.println("Am1-> " + x);} public void m2() {System.out.println("Am2-> " + this.x);} public void update() { x = 99;} } class B extends A { public void m2() {System.out.println("Bm2-> " + x);} public void m2(int y) {System.out.println("Bm2y-> " + y);} public void m3() {System.out.println("Bm3-> " + "called");} } class C extends B { public int y = x + 1; public void m2() {System.out.println("Cm2-> " + super.x);} public void m4() {System.out.println("Cm4-> " + super.super.x); }} //can't do super.super public void m5() {System.out.println("Cm5-> " + y);} } class D { public static void main (String[] args) { // B a0 = new A(); Dynamic type must be B or subclass of B // a0.m1(); cascading: prev line failed, so a0 can't be initialized // a0.m2(16); cascading: prev line failed, so a0 can't be initialized A b0 = new B(); System.out.println(b0.x); [prints "5"] b0.m1(); //[prints "Am1-> 5"] b0.m2(); //[prints "Bm2-> 5"] // b0.m2(61); m2 (int y) not defined in static type of b0 B b1 = new B(); b1.m2(61); //[prints "Bm2y-> 61"] b1.m3(); //[prints "Bm3-> called"] A c0 = new C(); c0.m2(); //[prints "cm2-> 5"] // C c1 = (A) new C(); Can't assign c1 to an A A a1 = (A) c0; C c2 = (C) a1; c2.m3(); [print Bm3-> called] // c2.m4(); C.m4() is invalid c2.m5(); //[print Cm5-> 6] ((C) c0).m3(); //[print Bm3-> called] Inheritance //(C) c0.m3(); NOT RUNTIME ERROR This would case the result of what the method returns and it returns void therefore compile-time error b0.update(); b0.m1(); [print Am1-> 99] } }
这篇关于2018 cs61b dis4的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-26MATLAB 中 A(7)=[];什么意思?-icode9专业技术文章分享
- 2024-11-26UniApp 中如何实现使用输入法时保持页面列表不动的效果?-icode9专业技术文章分享
- 2024-11-26在 UniApp 中怎么实现输入法弹出时禁止页面向上滚动?-icode9专业技术文章分享
- 2024-11-26WebSocket是什么,怎么使用?-icode9专业技术文章分享
- 2024-11-26页面有多个ref 要动态传入怎么实现?-icode9专业技术文章分享
- 2024-11-26在 UniApp 中实现一个底部输入框的常见方法有哪些?-icode9专业技术文章分享
- 2024-11-26RocketMQ入门指南:搭建与使用全流程详解
- 2024-11-26RocketMQ入门教程:轻松搭建与使用指南
- 2024-11-26手写RocketMQ:从入门到实践的简单教程
- 2024-11-25【机器学习(二)】分类和回归任务-决策树(Decision Tree,DT)算法-Sentosa_DSML社区版