四、程序阅读题
4.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 PrintNum{
public static void main(String args[]){
A a = new B();
System.out.println(a.f(3,5)); //【代码1】
B b = (B)a; //将a转化成B类并赋给b
System.out.println(b.g(3, 5)); //【代码2】
}
}
运行结果:
就是分别调用两个方法,没什么难度。
4.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类
public class PrintAdd{
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】
}
}
结果:
就是正常调用方法输出。
Vscode报错:Exception in thread "main" java.lang.IncompatibleClassChangeError: Class B does not implement the requested interface Com
解决方法:换个软件。
4.3.请说出E类中【代码】的输出结果
interface Com{
int add(int a,int b);
public static int get(int n){
return n;
}
//静态量,属于类
public default int see(int n){
return n;
}
//修饰接口
public default int look(int n){
return n;
}
}
class A implements Com{
public int add(int a,int b){
return a+b;
}
public int see(int n){
return n+1;
}
}
public class StudyCom{
public static void main(String args[]){
A a = new A();
int m = a.add(12, 6);
int n = Com.get(12);
int t = a.see(6);
int q = a.look(6);
System.out.printf("%d:%d:%d:%d",m,n,t,q); //代码
}
}
结果:
M:调用A类的add;n调用Com接口的add;t:调用A类的see;q:A类没有look,因此调用接口Com的look。
五、编程题
Animal.java
interface Animal{
abstract void cry();
abstract String getAnimalName();
}
Dog.java
public class Dog implements Animal{
public void cry(){
System.out.println("Dog cry!");
}
public String getAnimalName(){
String name = "Dog";
return name;
}
}
Cat.java
public class Cat implements Animal{
public void cry(){
System.out.println("Cat cry!");
}
public String getAnimalName(){
String name = "Cat";
return name;
}
}
Simulator.java
public class Simulator{
Animal animal;
public void playSound(Animal animal){
this.animal = animal;
System.out.println("AnimalName:"+animal.getAnimalName());
animal.cry();
}
}
Application.java
public class Application{
public static void main (String args[]){
Simulator simulator = new Simulator();
simulator.playSound(new Dog());
simulator.playSound(new Cat());
}
}
没什么难度,和上节课的编程思路一样,只是将类变成接口了。其余代码不变。
运行结果: