Is it possible to define custom types in java that work with primitives?
10,368
Solution 1
Auto-boxing and auto-unboxing only works with primitives. The concept you are talking about is similar to C++ conversions. Unfortunately, there is no such thing in Java. The best you can do is
Price myPrice = new Price(10.0);
Solution 2
No, you can't define your own primitive types for numerical quantities.
Declaring Price myPrice
means that the variable myPrice will be of type Price and will be used to as its instance.
You can have following valid.
Suppose you declare variable myPrice
of type Price
. Some instance variables can be accessed via that myPrice
reference.
Price myPrice = new Price();
myPrice.value = 10.0;
myPrice.currency = "Dollar";
etc ....
Author by
deltanovember
Updated on June 11, 2022Comments
-
deltanovember almost 2 years
For example the following is syntactically correct code
Double number = 10.0;
Is it possible to define my own class such as Price
Price myPrice = 10.0;
Actually compiles ?
-
Joachim Sauer almost 13 yearsStrictly speaking primitives can't be instantiated at all, they are not objects. Auto-boxing allows implicit creation of primitive wrapper objects in some cases, however.
-
Saurabh Gokhale almost 13 years@Joachim : value and currency are the instance variables of
Price
class. So they can be accessed viamyPrice
reference -
f1sh almost 13 yearsbut there's no
myPrice = new Price();
so line 2 will throw a NPE. That's what Joachim meant. EDIT: answered too late :-/ -
Saurabh Gokhale almost 13 years^ Yes ... Oops. Missed that. :-)