程序阅读分析题 1、interface Com { int MAX = 100; //【1】 void f(); } abstract class Animal implements Com { int MIN ; //【2】 } class Dog extends Animal{ void f(){ //【3】 MIN = 10; //【4】 MAX=20; //【5】 } } public class TestDemo{ public static void main(String[] arr){ Com c=new Dog(); System.out.println(c.MAX+”,”+c.MIN); //【6】 } } 请认真阅读上代码,请问哪几行代码有错?什么原因导致的?
时间: 2024-04-21 10:30:00 浏览: 23
代码中有两行错误,分别是第2行和第5行。
第2行错误的原因是抽象类Animal没有实现接口Com中的方法f(),因此Animal类必须也声明为抽象类。
第5行错误的原因是接口Com中的MAX常量是一个静态常量,无法被实例化对象(如Dog对象)所修改,因此会编译错误。应该将MAX常量声明为public static final,这样才能被Dog类访问到。
相关问题
1、interface Com { int MAX = 100; //【1】 void f();}abstract class Animal implements Com { int MIN ; //【2】}class Dog extends Animal{ void f(){ //【3】 MIN = 10; //【4】 MAX=20; //【5】 } }public class TestDemo{public static void main(String[] arr){Com c=new Dog();System.out.println(c.MAX+”,”+c.MIN); //【6】}}请认真阅读上代码,请问哪几行代码有错?什么原因导致的?
这段代码中有两行有错。
错误1:第2行 Animal类中的MIN变量没有赋初始值,而抽象类中的变量不会自动初始化,因此需要在构造方法中对其进行初始化,或者直接在声明时赋初值。
错误2:第5行 MAX变量是一个常量,接口中定义的常量默认是public static final的,也就是说它是不可改变的,因此在Dog类中不能对MAX进行赋值。
正确的代码应该是这样的:
```
interface Com {
int MAX = 100; // 【1】
void f();
}
abstract class Animal implements Com {
int MIN = 0; // 【2】
}
class Dog extends Animal {
void f() { // 【3】
MIN = 10; // 【4】
}
}
public class TestDemo {
public static void main(String[] arr) {
Com c = new Dog();
System.out.println(c.MAX + "," + ((Dog) c).MIN); // 【6】
}
}
```
这里将Animal类中的MIN变量直接在声明时赋值为0,也可以在Animal类的构造方法中进行初始化。
在输出中需要将c转换为Dog类型,才能访问MIN变量。
1、interface Com( int MAX=100;// 【1】 void f0; ) abstract class Animal implements Com ( int MIN; //【2】 ) class Dog extends Animal void f0t //【3】 MIN =10; // 【4】 MAX=20; //【5】 ] public class TestDemo( public static void main(String[] arr)( Com c=new Dog0; System.out.println(c.MAX+”,”+c.MIN);// 【6】) 一 请认真阅读上代码,请问哪几行代码有错?什么原因导致的?
有两行代码有错,分别是:
1. 第一行的参数值不能在接口中指定初始值,应该改为:
```
interface Com {
int MAX = 100;
void f0();
}
```
2. 第二行的变量MIN没有指定初始值,应该改为:
```
abstract class Animal implements Com {
int MIN;
}
```
这是因为接口中的变量默认为public static final,必须在声明时初始化,而抽象类中的实例变量需要在子类中初始化。