如下问题,解题,看大家如何解,修改。

花开到荼靡 2012-06-23 07:53:27
大家提供自己的参考下,看看大家如何修改的。

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

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

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


修改如下程序:
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

}*/
}
...全文
80 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
花开到荼靡 2012-06-23
  • 打赏
  • 举报
回复
sing和say的共同父类或超类或接口

不错。
brightyq 2012-06-23
  • 打赏
  • 举报
回复
这是?
有什么扩展的,散分帖?
qybao 2012-06-23
  • 打赏
  • 举报
回复
主程序有问题,就算sing和say是类,也不可能直接用类当参数,要么是sing.class之类的,要么就是new一个sing对象再当参数传入
如果sing和say是对象,比如这段主程序之前定义 Sing sing = new Sing()之类的,那么很显然,act方法接收的参数就是sing和say的共同父类或超类或接口

所以
可以采用接口
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的主代码部分
}
}

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧