Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 myPrice = 10.0;

Actually compiles ?

like image 253
deltanovember Avatar asked Jun 24 '11 07:06

deltanovember


People also ask

What is custom type in Java?

Java User-defined data types are the customized data types created by the developers by exploiting the special features offered by the Java language. This customized data type combines data types of a group of data elements with homogenous or assorted data types.

What is data type in Java how can we use primitive data types as objects?

What is a Primitive Data Type? The predefined data types of Java are known as primitive data types. The agenda of these data types is to determine the size and type of any values. It includes eight primitive data types: byte, long, short, int, double, float, char and boolean.

How do you create a primitive class in Java?

As the Java documentation explains: A primitive type is predefined by the language and is named by a reserved keyword. Show activity on this post. Simply No, You can not create primitive datatype. Primitive datatype means which are provided and existed in language feature.

Why we use primitive data type in Java?

The main reason primitive data type are there because, creating object, allocating heap is too costly and there is a performance penalty for it. As you may know primitive data types like int, float etc are most used, so making them as Objects would have been huge performance hit.


2 Answers

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);
like image 101
Nick Avatar answered Oct 17 '22 17:10

Nick


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 ....
like image 26
Saurabh Gokhale Avatar answered Oct 17 '22 15:10

Saurabh Gokhale