Reputation: 44051
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 ?
Upvotes: 7
Views: 15564
Reputation: 46395
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 ....
Upvotes: 2
Reputation: 3160
You can't extend Double
class, since it is final.
But you can extend Number
class and implement Comparable
interface - the way actual Double class is created.
Upvotes: 1
Reputation: 425003
No. It's hard-wired into the language.
Only primitives may be instantiated without the new
keyword, except String
, which although not a primitive, may be assigned using primitive syntax. ie both new String("foo")
and "foo"
will do it (note though that these are not exactly the same).
Upvotes: 0
Reputation: 5805
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);
Upvotes: 7