zomy2000
zomy2000

Reputation: 73

Use interface after passing reference of object to null JAVA

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

    }

}

Upvotes: 0

Views: 90

Answers (1)

sdgfsdh
sdgfsdh

Reputation: 37065

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;

Upvotes: 1

Related Questions