Is it possible to define custom types in java that work with primitives?

For example, syntactically correct code

Double number = 10.0; 

Is it possible to define my own class, for example Price

 Price myPrice = 10.0; 

Actually compiles?

+6
source share
4 answers

Auto-boxing and auto-unpacking work only with primitives. The concept you are talking about is similar to a C ++ conversion. Unfortunately, in Java there is no such thing. The best you can do is

 Price myPrice = new Price(10.0); 
+7
source

No, you cannot define your own primitive types for numeric values.

The Price myPrice means that the variable myPrice will be of type Price and will be used as an instance of it.

You can have a valid one.

Suppose you declare a variable myPrice type Price . Some instance variables can be accessed via this myPrice link.

 Price myPrice = new Price(); myPrice.value = 10.0; myPrice.currency = "Dollar"; etc .... 
+2
source

You cannot extend the Double class because it is final.

But you can extend the Number class and implement the Comparable interface - the real Double class is created .

0
source

Not. It is tightly connected with the tongue.

Only primitives can be created without the new keyword, except for String , which, although not primitive, can be assigned using primitive syntax. those. both new String("foo") and "foo" will be executed (note that this is not exactly the same).

0
source

Source: https://habr.com/ru/post/891270/


All Articles