简体   繁体   中英

Using Polymorphism Java

My goal is to print out that all the instruments are playing by creating the testInstrument.java file. For some reason I am getting an error for System.out.println(all[i].play());

testInstrument.java

package my_instruments;

public class testInstrument {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Guitar g = new Guitar();
        Flute f = new Flute();
        Piano p = new Piano();



        Instrument[] all = new Instrument[3];

        all[0] = g;
        all[1] = f;
        all[2] = p;

        for (int i=0; i<3; i++) {
            System.out.println(all[i].play());
        }


    }

}

Instrument.java

package my_instruments;

public class Instrument {

public Instrument() {

}

public void play() {
    System.out.println("Playing instrument");
}
}

Piano.java

package my_instruments;

public class Piano extends Instrument{
public Piano() {
    super();
}

public void play() {
    System.out.println("Playing piano");
}
}

Try this:

for (int i=0; i<3; i++) {
       all[i].play();
    }

The play method is already doing the printing and is not returning anything to print.

your play method() is doing the printing already System.out.println(); try removing the print statement from your for loop

for (int i=0; i<3; i++) {
    all[i].play();
}

or

for (Instrument i : all) {
    i.play();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM