一、选择
- 阅读下面的Java代码,能够填写在横线处的语句是
A. private int MAX_LOG_SIZE = 1000;
B. public void print() { }
C. private Boolean saveToFile(String fileNmae);
D. int getSize();
public interface ILog{
//---------
}
D
- 下列关于Java中接口的说法不正确的是
A. 接口中方法的访问修饰符默认为public
B. 接口中的方法如果写成void test();的形式,默认是抽象方法
C. 实现接口的类中在重写接口中方法时访问修饰符可以为protected
D. 当类实现接口时,需要实现接口中所有的抽象方法,否则需要将该类设置为抽象类
C
- 运行下列代码时,哪个位置会发生编译报错
A. 位置1 B. 位置2 C. 位置3 D. 不存在错误
interface A { //位置1
public static final int TEMP; //位置2
public abstract void info(); //位置3
}
B
- 在实现类中的划线处加入下列哪条代码可以调用 IAa 接口中默认的方法
A. IAa.show(); B. super.show(); C. IAa.super.show(); D. B.super.show();
//接口
public interface IAa {
default void show() {
System.out.println("我是默认方法");
};
}
//接口实现类
public class B implements IAa {
@Override
public void show() {
//------------
System.out.println("重写默认方法");
}
}
C
- 下列代码的运行结果是
A. 10temp B. temp10 C. 1010 D. temptemp
public interface IA {
int TEMP = 10;
}
public interface IB extends IA {
String TEMP = "temp";
}
public class Test implements IA, IB {
public static void main(String[] args) {
IA a = new Test();
IB b = new Test();
System.out.print(a.TEMP);
System.out.println(b.TEMP);
}
}
A
二、编程
- 使用接口的知识, 定义接口IFly,创建三个类Plane类、Bird类、Balloon类,分别重写接口中的fly( ) 方法,然后再测试类中进行调用。 程序运行参考效果如图所示:
任务分析:- 创建接口IFly( ) 方法:创建抽象方法 fly() 方法
- 创建子类:Plane 方法:实现接口中的方法fly( ),输出信息“飞机在天上飞”
- 创建子类:Bird 方法:实现接口中的方法fly( ),输出信息“小鸟在天空翱翔"”
- 创建子类:Balloon 方法:实现接口中的方法fly( ),输出信息“气球飞上天空”
- 创建测试类,分别创建Plane、Bird、Balloon类的对象,调用 fly( ) 方法,输出效果参考效果图
接口
public interface IFly {
public void fly();
}
子类
public class Plane implements IFly {
@Override
public void fly() {
System.out.println("飞机在天上飞");
}
}
public class Bird implements IFly {
@Override
public void fly() {
System.out.println("小鸟在天空翱翔");
}
}
public class Balloon implements IFly {
@Override
public void fly() {
System.out.println("气球飞上天空");
}
}
测试
public class Test {
public static void main(String[] args) {
IFly plane = new Plane();
IFly bird = new Bird();
IFly balloon = new Balloon();
plane.fly();
bird.fly();
balloon.fly();
}
}