请高手帮我做一下这个题?

ghd2000 2009-04-01 08:25:42
编写一个程序,新建一个父类Addition,父类中有一个抽象方法add(),add()方法在NumberAddtion类中将两个数字相加,而在TextConcatenation类中则连接两个String(字符串)。声明属性并在父类Addition的构造方法中初始化属性。
...全文
74 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sjzxqrj 2009-04-02
  • 打赏
  • 举报
回复

abstract class Addition <T>
{
T a,b;
public Addition(T a,T b)
{
this.a=a;
this.b=b;
}
public abstract T add();
}

class NumberAddtion extends Addition<Integer>
{
public NumberAddtion(Integer a, Integer b) {
super(a,b);
}

public Integer add() {
return this.a + this.b;
}

}

class TextConcatenation extends Addition<String>
{
public TextConcatenation(String a, String b) {
super(a,b);
}

public String add() {
return this.a + this.b;
}

}






承揽网站开发,SEO优化,毕业设计,OA,ERP,空间,域名,企业级管理系统 业务范围:[.net] [java]
Steve 2009-04-02
  • 打赏
  • 举报
回复
对一楼的改进一下.
1)用Java1.5的Generics简化类型转换
2)n和t不该用子类而应用父类定义子类具体化

abstract class Addition <T>
{
T a,b;
public Addition(T a,T b)
{
this.a=a;
this.b=b;
}
public abstract T add();
}

class NumberAddtion extends Addition<Integer>
{
public NumberAddtion(Integer a, Integer b) {
super(a,b);
}

public Integer add() {
return this.a + this.b;
}

}

class TextConcatenation extends Addition<String>
{
public TextConcatenation(String a, String b) {
super(a,b);
}

public String add() {
return this.a + this.b;
}

}


public class Test {
public static void main(String[] args) {
String s1="Hello ";
String s2="World!";
Integer n1 = 1;
Integer n2 = 2;
Addition<String> addS = new TextConcatenation(s1, s2);
Addition<Integer> addN = new NumberAddtion(n1, n2);
System.out.println(addS.add());
System.out.println(addN.add());
}

}
fireinjava 2009-04-02
  • 打赏
  • 举报
回复
顶下楼上

猿敲月下码 2009-04-01
  • 打赏
  • 举报
回复
应该还有更好的方法
abstract class Addition
{
Object a,b;
public Addition(Object a,Object b)
{
this.a=a;
this.b=b;
}
public abstract Object add();

}
class NumberAddtion extends Addition
{
public NumberAddtion(int a, int b) {
super(a, b);
}

public Object add() {
return (Integer)a+(Integer)b;
}
}
class TextConcatenation extends Addition
{

public TextConcatenation(String a, String b) {
super(a, b);
}

public Object add() {
return (String)a+(String)b;
}

}
public class Test {
public static void main(String[] args) {
int a=1,b=2;
String s="Hello ";
String s2="World!";
NumberAddtion n=new NumberAddtion(a,b);
TextConcatenation t=new TextConcatenation(s,s2);

System.out.println((Integer)n.add());
System.out.println((String)t.add());
}

}

67,515

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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