[英]Is it possible to define custom types in java that work with primitives?
For example the following is syntactically correct code 例如,以下是语法正确的代码
Double number = 10.0;
Is it possible to define my own class such as Price 是否可以定义我自己的类,如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. 您正在谈论的概念类似于C ++转换。 Unfortunately, there is no such thing in Java. 不幸的是,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. 声明Price myPrice
意味着变量myPrice将是Price类型并将用作其实例。
You can have following valid. 您可以拥有以下有效权。
Suppose you declare variable myPrice
of type Price
. 假设你声明变量myPrice
类型的Price
。 Some instance variables can be accessed via that myPrice
reference. 可以通过myPrice
引用访问某些实例变量。
Price myPrice = new Price();
myPrice.value = 10.0;
myPrice.currency = "Dollar";
etc ....
You can't extend Double
class, since it is final. 你不能扩展Double
类,因为它是最终的。
But you can extend Number
class and implement Comparable
interface - the way actual Double class is created . 但是你可以扩展Number
类并实现Comparable
接口 - 实际创建Double类的方式。
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. 只有原语可以在没有new
关键字的情况下被实例化,除了String
,虽然不是原语,但可以使用原语语法来分配。 ie both new String("foo")
and "foo"
will do it (note though that these are not exactly the same). 即new String("foo")
和"foo"
都会这样做(请注意,这些并不完全相同 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.