Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a constructor that takes arguments without 'new'

Tags:

java

class

I want to make a class that works like String, i.e doesn't require new String("value");.
For example:

public class Number { ... }

// main
Number num = 5;

Is it possible?

like image 796
Gofilord Avatar asked Mar 02 '26 10:03

Gofilord


1 Answers

Short answer is no.

The long answer, you wouldn't want that behavior.

The cool thing about a strict OO language is you can ensure that an object is an object... the problem with java is that its a class based language, and less of an OO language... which causes oddities like this.

int myInt = 5; //primitive assignment.

This is a value, it is not an object and does not conform to the standards of what an object represents in Java.

Integer myInt = new Integer(5);

is creating a new object in memory, assigning a reference to it, and then any "passing" of this object happens by reference.

There are many frameworks that can give you a semblance of this assignment, but the new lets you know that you are creating a brand new object and not simply the value of some random section of memory that happens to be declared as a string of integer bits.

like image 175
AnthonyJClink Avatar answered Mar 05 '26 00:03

AnthonyJClink