编写一个程序,新建一个父类Addition,父类中有一个抽象方法add(),add()方法在NumberAddtion类中将两个数字相加,而在TextConcatenation类中则连接两个String(字符串)。声明属性并在父类Addition的构造方法中初始化属性。

解决方案 »

  1.   

    应该还有更好的方法
    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());
    }

    }
      

  2.   

    对一楼的改进一下.
    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());
    }

    }
      

  3.   


    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]