日期:2014-05-20  浏览次数:20699 次

如下问题,解题,看大家如何解,修改。
大家提供自己的参考下,看看大家如何修改的。 

根据提供的主程序修改程序,定义不同的行为类。 主程序中Say and Sing 不是String。

比如 say 和 sing 各定义为类。看看大家发挥,
根据这个主程序:谢谢
Java code
.....
    Person father = new Father();
        father.setContent("How are you");
        father.act(sing);

        Mother mother = new Mother();
        mother.act(say);
....



修改如下程序:
Java code
public class PloyTest1
{
    
    public  void say(Person person)
    {
       person.say();
    }
 
    public  void sing(Person person)
    {
       person.sing();
    }
 
    public static void main(String[] args)
    {
       PloyTest1 test = new PloyTest1();
 
       Person person = new Father();
       // test.say(person);
       test.sing(person);
 
       Mother mother = new Mother();
       test.say(mother);
 
    }
 
}
 
 //class Person
 
abstract class Person
{
    /*public void say()
    {
       System.out.println("person is saying");
    }*/
 
    /*public void sing()
    {
       // TODO Auto-generated method stub
       System.out.println("");
    }*/
    
    public abstract void say();
    
    public void sing(){}
}
 
class Father extends Person
{
    public void say()
    {
       System.out.println("father is saying: How are you?");
    }
 
    @Override
    public void sing()
    {
       // TODO Auto-generated method stub
       System.out.println("father sing: how are you");
    }
}
 
class Mother extends Person
{
    public void say()
    {
       System.out.println("mother is saying: I am fine");
    }
 
    /*@Override
    public void sing()
    {
       // TODO Auto-generated method stub
       
    }*/
}



------解决方案--------------------
主程序有问题,就算sing和say是类,也不可能直接用类当参数,要么是sing.class之类的,要么就是new一个sing对象再当参数传入
如果sing和say是对象,比如这段主程序之前定义 Sing sing = new Sing()之类的,那么很显然,act方法接收的参数就是sing和say的共同父类或超类或接口

所以
可以采用接口
Java code
interface IMouthAction {
    void action();
}

class Sing implement IMouthAction {
    public void action() {System.out.println("sing");}
}

class Say implement IMouthAction {
    public void action() {System.out.println("say");}
}

abstract class Person {
    public void act(IMouthAction action) {action.action();}
}

class Father extends Person {}
class Mather extends Person {}

public class Main {
    public static void main(String[] args) {
        IMouthAction sing = new Sing();
        IMouthAction say = new Say();

        ... //LZ的主代码部分
    }
}