3

May be the title will misguide you.

String str ="abcd";

In the above code String is a class and without using new we can create an object with value. Now I have a class Number.java in which I have to assign some number as shown below.

Number no = 23;

How to create such class.

Maxime Rouiller
  • 13,453
  • 9
  • 55
  • 106
JAVA_CAT
  • 563
  • 2
  • 11
  • 26

5 Answers5

1

I would normally say that you should be using Operator Overloading. But this feature does not exist in Java.

See here: Operator overloading in Java

Community
  • 1
  • 1
Maxime Rouiller
  • 13,453
  • 9
  • 55
  • 106
1

You can't directly assign value to Object like Strings.

If you really want to achieve the same thing, I would suggest you to create a Factory of pre-defined initialized objects and get the required object from Factory by using Prototype pattern or FactoryMethod pattern.

Sample code:

import java.util.concurrent.atomic.*;

public class PrototypeFactory
{
    public class NumberPrototype
    {
        public static final String THIRTY_TWO = "32";
        public static final String FORTY_ONE = "41";

    }

    private static java.util.Map<String , AtomicInteger> prototypes = new java.util.HashMap<String , AtomicInteger>();

    static
    {
        prototypes.put(NumberPrototype.THIRTY_TWO, new AtomicInteger(32));
        prototypes.put(NumberPrototype.FORTY_ONE, new AtomicInteger(43));

    }

    public static AtomicInteger getInstance( final String s) {
        //return (AtomicInteger)(prototypes.get(s)).clone();
        return ((AtomicInteger)prototypes.get(s));
    }
    public static void main(String args[]){
        System.out.println("Prototype.get(32):"+PrototypeFactory.getInstance(NumberPrototype.THIRTY_TWO));
    }
}

output:

Prototype.get(32):32
Ravindra babu
  • 45,953
  • 8
  • 231
  • 206
0

You can't.

The Java compiler is just providing you with a syntactical shortcut.

From the Java Tutorial:

[...] a string literal [is] a series of characters in your code that is enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler creates a String object with its value

Mikel Rychliski
  • 3,240
  • 5
  • 19
  • 26
0

Actually this type of assignment does work for the primitive wrapper classes due to auto-boxing

Integer n = 23;
sjrcgtek
  • 18
  • 6
0

You can't since the primitive values are part of the java language, if you wanted to make a class to be "initialized" like that you should add it to the java parse or something like that.