Java2实⽤教程(第5版)耿祥义版习题六⼀、问答题
1.接⼝中能声明变量吗?
2.接⼝中能定义⾮抽象⽅法吗?
3.什么叫接⼝的回调?
4.接⼝中的常量可以不指定初值吗?
5.可以在接⼝中只声明常量,不声明抽象⽅法吗?
⼆、选择题
1.下列哪个叙述是正确的
A.⼀个类最多可以实现两个接⼝。
B.如果⼀个抽象类实现某个接⼝,那么它必须要重写接⼝中的全部⽅法。
C.如果⼀个⾮抽象类实现某个接⼝,那么它可以只重写接⼝中的部分⽅法。
D.允许接⼝中只有⼀个抽象⽅法。
2.下列接⼝中标注的(A,B,C,D)中,哪两个是错误的?
interface Takecare {
protected void speakHello();          //A
public abstract static void cry();        //B
int f();                            //C
abstract float g();                  //D
}
3.将下列(A,B,C,D)哪个代码替换下列程序中的【代码】不会导致编译错误。
A.public int f(){return 100+M;}
B.int f(){return 100;}
C.public double f(){return 2.6;}。
D.public abstract int f();
interface Com {
int M = 200;
int f();
}
class ImpCom implements Com {
【代码】
}
三、阅读程序
1.请说出E类中【代码1】,【代码2】的输出结果。
interface A {
double f(double x,double y);
}
class B implements A {
public double f(double x,double y) {
return x*y;
}
int g(int a,int b) {
return a+b;
}
}
public class E {
public static void main(String args[]) {
A a = new B();
System.out.println(a.f(3,5)); //【代码1】java接口可以创建对象吗
B b = (B)a;
System.out.println(b.g(3,5)); //【代码2】
}
}
2.请说出E类中【代码1】,【代码2】的输出结果。interface Com {
int add(int a,int b);
}
abstract class A {
abstract int add(int a,int b);
}
class B extends A implements Com{
public int add(int a,int b) {
return a+b;
}
}
public class E {
public static void main(String args[]) {
B b = new B();
Com com = b;
System.out.println(com.add(12,6)); //【代码1】
A a = b;
System.out.println(a.add(10,5));  //【代码2】
}
}
四、编程题(参考例⼦6)
该题⽬和第5章习题5的编程题类似,只不过这⾥要求使⽤接⼝⽽已。
设计⼀个动物声⾳“模拟器”,希望模拟器可以模拟许多动物的叫声。要求如下:
1. 编写接⼝Animal
Animal接⼝有2个抽象⽅法cry()和getAnimaName(),即要求实现该接⼝的各种具体动物类给出⾃⼰的叫声和种类名称。
1. 编写模拟器类Simulator
该类有⼀个playSound(Animal animal)⽅法,该⽅法的参数是Animal类型。即参数animal可以调⽤实现Animal接⼝类重写的cry()⽅法播放具体动物的声⾳、调⽤重写的getAnimalName()⽅法显⽰动物种类的名称。
1. 编写实现Animal接⼝的Dog类和Cat类
图6.14是Simulator、Animal、Dog、Cat的UML图。
1. 编写主类Application(⽤户程序)
在主类Application的main⽅法中⾄少包含如下代码:
Simulator simulator = new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
⼀、问答题
1.不能。
2.不能。
3.可以把实现某⼀接⼝的类创建的对象的引⽤赋给该接⼝声明的接⼝变量中。那么该接⼝变量就可以调⽤被类实现的接⼝中的⽅法。4.不可以。
5.可以。
⼆、选择题
1.D。2.AB。3.B。
三、阅读程序
1.【代码1】:15.0。【代码2】:8。
2.【代码1】:18。【代码2】:15。
四、编程题
Animal.java
public interface Animal {
public abstract void cry();
public abstract String getAnimalName();
}
Simulator.java
public class Simulator {
public void playSound(Animal animal) {
System.out.print("现在播放"+AnimalName()+"类的声⾳:");
<();
}
}
Dog.java
public class Dog implements Animal {
public void cry() {
System.out.println("汪汪...汪汪");
}
public String getAnimalName() {
return "狗";
}
}
Cat.java
public class Cat implements Animal {
public void cry() {
System.out.println("喵喵...喵喵");
}
public String getAnimalName() {
return "猫";
}
}
Application.java
public class Example5_13 {
public static void main(String args[]) {
Simulator simulator = new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。