一个简单的小程序,有些地方不是很懂,求大神讲解。
import java.util.*;
interface Instrument5 {
// Compile-time constant:
public static final int i = 5;
public void play();
public String what();
public void adjust();
}
class Wind5 implements Instrument5 {
public void play() {
System.out.println("Wind5.play()");
}
public String what() { return "Wind5"; }
public void adjust() {}
}
class Percussion5 implements Instrument5 {
public void play() {
System.out.println("Percussion5.play()");
}
public String what() { return "Percussion5"; }
public void adjust() {}
}
class Stringed5 implements Instrument5 {
public void play() {
System.out.println("Stringed5.play()");
}
public String what() { return "Stringed5"; }
public void adjust() {}
}
class Brass5 extends Wind5 {
public void play() {
System.out.println("Brass5.play()");
}
public void adjust() {
System.out.println("Brass5.adjust()");
}
}
class Woodwind5 extends Wind5 {
public void play() {
System.out.println("Woodwind5.play()");
}
public String what() { return "Woodwind5"; }
}
public class Music5 {
static void tune(Instrument5 i) {
i.play();
}
static void tuneAll(Instrument5[] e) {
for(int i = 0; i < e.length; i++)
tune(e[i]);
}
public static void main(String[] args) {
Instrument5[] orchestra = new Instrument5[5];
int i = 0;
orchestra[i++] = new Wind5();
orchestra[i++] = new Percussion5();
orchestra[i++] = new Stringed5();
orchestra[i++] = new Brass5();
orchestra[i++] = new Woodwind5();
tuneAll(orchestra);
}
}
中的public class Music5 {
static void tune(Instrument5 i) {
i.play();
}
static void tuneAll(Instrument5[] e) {
for(int i = 0; i < e.length; i++)
tune(e[i]);
}
public static void main(String[] args) {
Instrument5[] orchestra = new Instrument5[5];
int i = 0;
orchestra[i++] = new Wind5();
orchestra[i++] = new Percussion5();
orchestra[i++] = new Stringed5();
orchestra[i++] = new Brass5();
orchestra[i++] = new Woodwind5();
tuneAll(orchestra);
}
}
这段看不怎么明白,本人新手,求讲解,多谢了。
------解决方案--------------------这个就是new了五个对象,而且由于多态,Instrument5定义的引用可以指向它的实现类,况且Brass5和WoodWind5继承自Wind5,所以这些都可以看成是Instrument5的实例一样。
------解决方案--------------------具体那一块地方不明白能说清楚吗,这样叫人很难回答
------解决方案--------------------
static void tune(Instrument5 i) {
i.play();
}
static void tuneAll(Instrument5[] e) {
for(int i = 0; i < e.length; i++)
tune(e[i]);
}
public static void main(String[] args) {
Instrument5[] orchestra = new Instrument5[5];//得到5个接口
int i = 0;
orchestra[i++] = new Wind5();//多态,父类引用指向子类对象
orchestra[i++] = new Percussion5();//多态,父类引用指向子类对象
orchestra[i++] = new Stringed5();//多态,父类引用指向子类对象
orchestra[i++] = new Brass5();//多态,父类引用指向子类对象
orchestra[i++] = new Woodwind5();//多态,父类引用指向子类对象