0

Is it possible to create a number-like class in Java that would allow objects to be created like this:

MyClass x = 3;

Instead of this:

MyClass x = new MyClass(3);

And could be used like this:

float i = x/2;

Instead of this:

float i = x.value()/2;

?

Jecke
  • 239
  • 2
  • 13

1 Answers1

2

For your first example:

MyClass x = 3;

This will never be possible, since the 3 in this case is a primitive type, which is an int and not a real Object like MyClass. This simply will not work since Java is not designed like that.

For your second example:

float i = x / 2;

You are looking for operator overloading. Unfortunately this is not supported in Java: Operator overloading in Java

So to answer your question:

No. You can't do any of this in Java.

gi097
  • 7,313
  • 3
  • 27
  • 49
  • 1
    can I at least `typedef float MyType`? – Jecke Dec 13 '18 at 14:00
  • 1
    seems like I can't do that either. Oh god, java suuuucks. How on earth am I supposed to create an alias for float when it's used for a specific purpose? – Jecke Dec 13 '18 at 21:04
  • Nope. Java is very limited. You could try to use C# which has support for the elements you want and has a lot of similarities of Java. – gi097 Dec 14 '18 at 08:07
  • If I could, I would, unfortunately the choice of language wasn't mine. Thanks! – Jecke Dec 14 '18 at 13:39