vendredi 25 septembre 2015

How to check the type of an object without using instance of or getClass()

Example situation: I have a television abstract superclass. Two subclasses inherit from it. Both of these two subclasses have factory methods to create their own remotes. Remote is a superclass and it has two subclasses. The remotes are able to change their respective Television's channel(in this case, a samsung remote should work with any samsung TV).

The remote classes have a changeChannel method take in a television and a channel. My question is, is there a way that I can keep this hierarchy with the methods and parameters that it currently has and not have to use conditional logic for a remote to be able to only change the channel of its own brand of television. I have provided the code below.

import java.util.*;

public abstract class Television{
    private int channel;

    public abstract Remote makeRemote();

    public int getChannel(){
        return channel;
    }

    public void setChannel(int c){
        channel=c;  
    }
}

import java.util.*;


public class SamsungTelevision extends Television{
    private int channel;

    public Remote makeRemote(){
        return new SamsungRemote();
    }   

}

import java.util.*;


public class SonyTelevision extends Television{
    private int channel;

    public Remote makeRemote(){
        return new SonyRemote();
    }

}

import java.util.*;


public abstract class Remote{

    public abstract void changeChannel(Television t,int channel);
}

import java.util.*;


public class SamsungRemote extends Remote{

    public void changeChannel(Television t,int channel){
        t.setChannel(channel);
        System.out.println("Samsung: Channel has been switched");
    }

}

import java.util.*;


public class SonyRemote extends Remote{

    public void changeChannel(Television t,int channel){
        t.setChannel(channel);
        System.out.println("Sony: Channel has been switched");
    }
}

import java.util.*;


public class Driver{
    public static void main(String[] args){
        Television t = new SamsungTelevision();
        Television t1 = new SonyTelevision();
        Remote r=t.makeRemote();
        r.changeChannel(t,35);
        System.out.println("Samsung current channel: " + t.getChannel());
        r.changeChannel(t1,37);
        System.out.println("Sony current channel: " + t1.getChannel());
    }
}

Aucun commentaire:

Enregistrer un commentaire