假如有很多if else,为了体现面向对象,用什么来代替呢?
if(animal.IsCat()) {}else if(animal.IsDog()) {}
else if(animal.IsKoala()) {}
. . .else if(A.isType(Type10)) { }
上面的代码段中使用一个对象命名为“动物。“假设有一个动物的类层次结构。下面哪一项技术可以取代是以if - then - else构造
1持久?
2Messaging
3抽象
4封装
5多态 /**
* File:Animal.java
* ------------------
* Polymorphism
*/
package org.cudemo;
/**
* @author isaacxu
**
*/
public class Animal{
public void spark( ) {
}
}/**
* File:Cat.java
* -----------------
* Cat objects are Animal
* because they have the same interface:
*/
package org.cudemo;
public class Cat extends Animal{
// Redefine interface method
public void spark() {
System.out.println("I am a Cat!");
}
}
/**
* File:Dog.java
* ---------------
* Dog objects are Animal
* because they have the same interface:
*/
package org.cudemo;
public class Dog extends Animal{
// Redefine interface method
public void spark( ) {
System.out.println("I am a Dog!");
}
}
/**
* File:Koala.java
* -------------------------
* Koala objects are Animal
* because they have the same interface:
*/
package org.cudemo;
/**
* @author isaacxu
*
*/
public class Koala extends Animal{
// Redefine interface method
public void spark( ) {
System.out.println("I am a Koala!");
}
}
/**
* File:Sound.java
* ---------------
* Test file like <Think in Java>:Inheritance & upcasting
*/
package org.cudemo;
public class Sound {
public static void barking(Animal a) {
// ...
a.spark();
}
public static void barkingAll(Animal[] all) {
for(Animal i : all)
barking(i);
}
/**
* @param args
*/
public static void main(String[] args) {
Animal[] pets = {
new Cat(),
new Dog(),
new Koala()
//.....
};
barkingAll(pets);
}
}
回复 2# isaacxu
谢谢啊,例子很好
这个叫多态么? 看你的代码差不多是多态,但还是要看具体操作了。
页:
[1]