COMP 3670 - Understanding Objects

Alex Bunardzic, British Columbia Institute Of Technology (BCIT)

Code examples (Week 06):

In order to illustrate the concepts presented during Lecture #6, we have introduced a Java application. This application is supposed to demonstrate the use of polymorphism. We've started with a simple interface Instrument (we'll keep things simple by assuming that the instrument understands only one message -- play):

interface Instrument{
    public void play();
}


We have implemented several instruments (piano, guitar,...):

class Piano implements Instrument {
    public void play(){
        System.out.println("playing the piano...");
    }
}

class Guitar implements Instrument {
    public void play(){
        System.out.println("playing the guitar...");
    }
}

class Flute implements Instrument {
    public void play(){
        System.out.println("playing the flute...");
    }
}



Finally, the Conductor will accept the music score, and will play it by sending the messages to each instrument:

class Conductor {
    public static void main(String[] args) {
        try{
            for(int i = 0; i < args.length; i++){
            Instrument instrument = (Instrument)Class.forName(args[i]).newInstance();
            instrument.play();
            }
        }
        catch(Exception e){
            System.out.println("Problem in conductor " + e);
        }
    }
}