英文:
Use interface after passing reference of object to null JAVA
问题
import java.util.Random;
public class DVDPlayer implements RemoteControl {
String type;
int currentVolume;
@Override
public int volumeUp() {
currentVolume += 2;
return currentVolume;
}
public static void main(String Args[]) {
Random r = new Random();
Object RC = null;
if (r.nextFloat() < 0.5) {
// 将此 remoteControl 对象引用指向 TV 对象
RC = new TV();
} else {
// 指向 DVDPlayer 对象
RC = new DVDPlayer();
}
RC.volumeUp();
}
}
英文:
How can I use a method in the interface RemoteControl in object RC while doing it this way (compiler refuses since "object" does not implement RemoteControl).
import java.util.Random;
public class DVDPlayer implements RemoteControl {
String type;
int currentVolume;
@Override
public int volumeUp() {
currentVolume += 2;
return currentVolume;
}
public static void main(String Args[]) {
Random r = new Random();
Object RC = null;
if (r.nextFloat() < 0.5) {
// make this remoteControl object reference to TV object
RC = new TV();
} else {
// to DVDPlayer object
RC = new DVDPlayer();
}
RC.volumeUp();
}
}
答案1
得分: 1
你已将实例 RC
的类型指定为 Object
,但该类型没有 volumeUp
方法。
你可能想要将 RC
的类型设定为 RemoteControl
:
RemoteControl RC = null;
英文:
You have given the instance RC
the type Object
, which does not have the method volumeUp
.
What you probably meant to do is give RC
the type RemoteControl
:
RemoteControl RC = null;
专注分享java语言的经验与见解,让所有开发者获益!
评论