package musical;
public class instrument {
public void makeSound(){
System.out.println("乐器可以演奏!");
}
}
package musical;
public class Erhu extends instrument{
@Override
public void makeSound() {
System.out.println("乐手正在演奏二胡!");
}
public void like(){
System.out.println("样子像一个弓箭!");
}
}
package musical;
public class Piano extends instrument {
@Override
public void makeSound() {
System.out.println("乐手正在演奏钢琴!");
}
public void like(){
System.out.println("样子像一个机器!");
}
}
package musical;
public class Violin extends instrument {
@Override
public void makeSound() {
System.out.println("乐手正在演奏小提琴!");
}
public void like(){
System.out.println("样子像一个葫芦!");
}
}
package musical;
public class Musician {
instrument i;
public Musician(instrument instrument){
this.i = instrument;
}
public void play(){
i.makeSound();
}
public void lookLike(){
if(i instanceof Erhu){//instance,可以在程序运行
// 阶段判断某个引用指向的对象是否为某一类型,
// 向下转型一定要判断类型,这是企业的代码规范。
// ((Erhu) i).like();
Erhu erhu = (Erhu)i;
erhu.like();
}
if(i instanceof Violin){
Violin violin = (Violin) this.i;
violin.like();
}
if (i instanceof Piano){
Piano piano = (Piano)i;
piano.like();
}
}
}
package musical;
public class Test {
public static void main(String[] args) {
//子转父
instrument i = new Violin();//向上转型(自然转换),可理解为小提琴是一个乐器
i.makeSound();
//父转子,向下转型(强制转换),需要子类中有特有的方法时,才可以编译
instrument ii = new Piano();
((Piano)ii).like();
Piano p = (Piano)ii;
p.like();
Musician musician = new Musician(new Erhu());
musician.play();
musician.lookLike();
}
}
结果:
若有问题,请指教!