Reputation: 97
Suppose this piece of code:
public class Int {
public int value;
public Int () {
this.value = 0;
}
public Int (int value) {
this.value = value;
}
@Override
public String toString () {
return Integer.valueOf (this.value).toString ();
}
}
Using a public attribute, I can access to the value of the attribute using:
Int a = new Int ();
int x = a.value;
I want to ask if there is a way to make this:
Int a = new Int (3);
Int b = new Int (11);
int x = a + b;
instead of:
...
int x = a.value + b.value;
EDIT
Sorry, mea culpa! I know that Java does not support operator overloading. I wrote bad examples.
Int a = new Int (12);
int x = a.value;
There is a way where I can write the code above in this way?
Int a = new Int (12);
int x = a;
So, what I'm asking is if it's possible to access to a specific attribute of a class omitting the name of the attribute.
Upvotes: 0
Views: 120
Reputation: 206796
Besides the fact that Java does not support user-specified operator overloading, there is also no mechanism to do auto-(un)boxing with your own classes.
Auto-(un)boxing only works with the 8 standard wrapper classes (Boolean
, Byte
, Short
, Character
, Integer
, Long
, Float
and Double
) as defined in paragraph 5.1.7 and 5.1.8 of the Java Language Specification.
So there is no way to make this work:
// Your own class Int
class Int { ... }
Int x = new Int(12);
int y = x; // auto-unboxing, not possible with Int
Upvotes: 1
Reputation: 6149
Java does not allow operator overloading (except fot Strings), so the +
operator cannot be used to "add" custom classes like your Int
.
Which means that, in your case, you cannot use the +
operator to do Int x = a + b;
.
The correct way to do this in an Object-Oriented language like Java, would be to add a plus
(or add
) method to you Int
class to perform this operation :
public Int plus(Int other) {
return new Int(this.value + other.value);
}
EDIT : to answer your new question...
The answer is still no, you can't define custom boxing/unboxing rules. The compiler will compare the type of the reference (int
) to the type of the instance (the custom Int
class), find they are not in the same hierarchy, and emit a compilation error.
The rules that allow the Number
wrappers (Integer
, Long
, etc.) to be seamlessly transformed to/from primitive types are special exceptions documented in the Java Language Specification.
Upvotes: 0