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 ?
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);
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 ....
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 .
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.