I understand that we can create different methods to define the actions into the class. Also, it's interesting for me to define math operations for my own class. Is it possible? For example, assuming we have a class:
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;
}
}
Later I would like to use for example:
User u1;
User u2;
User u3;
...
// Can it be possible?
u3 = u2 + u1;
u3 = u2 - u1;
Here is a code for working:
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);
}
}
OUTPUT:
They equals
a & a
b & b
c & c
Can I implement math operations like "+", "-", and other own operations for own objects of classes. Thank you.