Note.java 一个枚举类
package Lesson8Polymorphism.music;
public enum Note
{
MIDDLE_C, C_SHARP, B_FLAT;
}
music5.java
/**
* 书本:《Thinking In Java》
* 功能:接口
* 文件:Music.java
* 时间:2015年4月2日16:50:48
* 作者:cutter_point
*/
package Lesson9Interfaces.music5;
import java.util.Scanner;
import Lesson8Polymorphism.music.Note;
import static net.mindview.util.Print.*;
interface Instrument
{
int VALUES = 5; //默认是static和final的
void paly(Note n); //这里不能对方法进行实现
void adjust();
}
class Wind implements Instrument //必须实现接口的所有方法
{
@Override
public void paly(Note n)
{
print(this + ".play() " + n);
}
@Override
public void adjust()
{
print(this + ".adjust()");
}
public String toString()
{
return "Wind()";
}
}
class Percussion implements Instrument
{
@Override
public void paly(Note n)
{
print(this + ".play() " + n);
}
@Override
public void adjust()
{
print(this + ".adjust()");
}
public String toString()
{
return "Percussion()";
}
}
class Stringed implements Instrument
{
@Override
public void paly(Note n)
{
print(this + ".play() " + n);
}
@Override
public void adjust()
{
print(this + ".adjust()");
}
public String toString()
{
return "Stringed()";
}
}
class Brass extends Wind
{
public String toString()
{
return "Brass";
}
}
class Woodwind extends Wind
{
public String toString()
{
return "Woodwind";
}
}
public class Music5
{
static void tune(Instrument i)
{
i.paly(Note.MIDDLE_C); //MIDDLE_C, C_SHARP, B_FLAT;
}
static void tuneAll(Instrument[] e)
{
//一个个取出来调用tune函数
for(Instrument i : e)
{
tune(i);
}
}
public static void main(String [] args)
{
// Scanner s = new Scanner(System.in);
// System.out.println(s.next());
Instrument[] orchestra =
{
new Wind(),
new Percussion(),
new Stringed(),
new Brass(),
new Woodwind()
};
tuneAll(orchestra);
}
}
输出结果:
Wind().play() MIDDLE_C obj1
Percussion().play() MIDDLE_C obj1
Stringed().play() MIDDLE_C obj1
Brass.play() MIDDLE_C obj1
Woodwind.play() MIDDLE_C obj1