使用接口在将对象引用传递给 null 后,JAVA。

huangapple go评论70阅读模式
英文:

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() &lt; 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;

huangapple
  • 本文由 发表于 2020年4月11日 04:21:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/61148100.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定