如何为Java中的clasess或对象定义数学运算?

时间:2017-06-08 13:44:46

标签: java class math

我知道我们可以创建不同的方法来定义类中的动作。另外,为我自己的班级定义数学运算对我来说很有趣。可能吗?例如,假设我们有一个类:

public User{
  String name;
  //... other fields
  public String setName(String sn){
   return this.name = sn;
  }

  public String addClass(User u){
   return this.name = this.name + u.name;
  }
}

后来我想用例如:

User u1;
User u2;
User u3;
...
// Can it be possible?
u3 = u2 + u1;
u3 = u2 - u1;

以下是工作代码:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class NewClass1 {

    static Map<String, String> map = new HashMap<String, String>();
    static Map<String, String> map2 = new HashMap<String, String>();
    static Map<String, String> result = new HashMap<String, String>();

    public static Map<String, String> mapAB4(Map m1, Map m2) {
        Map<String, String> new_map = new HashMap<String, String>();
        Set<String> i1 = map.keySet();
        Set<String> i2 = map2.keySet();

        if (m1.size() > m2.size()) {
            new_map.put("c", "a");
            System.out.println("First is bigger");
        }
        if (m1.size() < m2.size()) {
            new_map.put("c", "b");
            System.out.println("Second is bigger");
        }
        if (m1.size() == m2.size()) {
            new_map.put("a", "a");
            new_map.put("b", "b");
            new_map.put("c", "c");
            System.out.println("They equals");
        }

        Iterator it = new_map.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            System.out.println(pair.getKey() + " & " + pair.getValue());
        }
        return new_map;
    }

    public static void main(String[] args) {
        map.put("1_key1", "1_value1");
        map.put("1_key2", "1_value2");
//        map2.put("1_key3", "1_value3");
        map2.put("2_key1", "2_value1");
        map2.put("2_key2", "2_value2");

        result = mapAB4(map, map2);

    }
}

输出:

They equals
a & a
b & b
c & c

我可以实现像&#34; +&#34;,&#34; - &#34;这样的数学运算,以及自己的类对象的其他操作。谢谢。

0 个答案:

没有答案