你是否看过JAVA核心技术,里面讲到类的继承里面的“上塑造型”。你可以这样写
class a
{
void a()
{
}
}class a1 extends a
{
void a()
{
....
}
}
class a2 extends a
{
void a()
{
...
}
}a b1 = new a1();
a b2 = new a2();这就是“上塑造型”,b1.a()和b2.a()的结果你可以看到他们是被重载以后的方法,而不是
a中的方法,我想这个大概是你要达到的效果.如果你知道更详细的话,可以看看我提到的那本书,里面讲的很清楚
class a
{
void a()
{
}
}class a1 extends a
{
void a()
{
....
}
}
class a2 extends a
{
void a()
{
...
}
}a b1 = new a1();
a b2 = new a2();这就是“上塑造型”,b1.a()和b2.a()的结果你可以看到他们是被重载以后的方法,而不是
a中的方法,我想这个大概是你要达到的效果.如果你知道更详细的话,可以看看我提到的那本书,里面讲的很清楚
Instrument5 instr; intstr=new Wind5();
//或instr=new Percussion5(); 这样你执行方法
intstr.play()就会动态绑定到Wind5的实现上去。这个还不能算是一个模式吧,只是多态的一个例子。
// Polymorphism in Javaclass Shape {
void draw() {}
void erase() {}
}class Circle extends Shape {
void draw() {
System.out.println("Circle.draw()");
}
void erase() {
System.out.println("Circle.erase()");
}
}class Square extends Shape {
void draw() {
System.out.println("Square.draw()");
}
void erase() {
System.out.println("Square.erase()");
}
}class Triangle extends Shape {
void draw() {
System.out.println("Triangle.draw()");
}
void erase() {
System.out.println("Triangle.erase()");
}
}public class Shapes {
public static Shape randShape() {
switch((int)(Math.random() * 3)) {
default: // To quiet the compiler
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
}
public static void main(String[] args) {
Shape[] s = new Shape[9];
// Fill up the array with shapes:
for(int i = 0; i < s.length; i++)
s[i] = randShape();
// Make polymorphic method calls:
for(int i = 0; i < s.length; i++)
s[i].draw();
}
} ///:~
看来是这个了,看看对不?
s[i].draw();
以上两行,看来你已经理解了上塑的含义
<<
switch((int)(Math.random() * 3)) {
default: // To quiet the compiler
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
>>
这段代码是否不好?如果我们需要增加新的Shape比如Pentangle,你的修改是否很大?
public static void main(String[] args) {
Instrument5 instr;
//这一段怎么写,让instr或是wind5或是Percussion5;
/*
根据你的条件 new 不同的类,比如: instr = new wind5();
*/
instr.play //可能是 Wind5 也可能是Percussion5,就是上边的怎么样让instr通过一缎程序,知道他到底执行那个方法??????
}