Reputation: 6641
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?
Upvotes: 3
Views: 2822
Reputation: 109547
No, but if you are looking to syntactic alternatives, there are some alternatives to constructors, that have their application.
Enums - not what you are looking for.
Static factory methods.
Rule x = Rules.def("abc");
Rule y = def("abc"); // Static import
public abstract class Rules { // Factory
public static Rule def(String s):
(One can drop the class name not only by a static import, but also by being inside a super class.)
class Grammar { protected Rule def(String s) { ... } }
Grammar g = new Grammar() {{
Rule x = def("abc");
}};
Builders, fluent API
Grammar g = GrammarBuilder.grammar("Pascal")
.rule("S")
.seq()
.keyword("PROGRAM");
.nont("Decl")
.nont("Block")
.endseq()
.endrule()
.rule("Decl")
...
Builders, fluent API
Grammar g = grammar("Pascal",
rule("S",
seq(
.keyword("PROGRAM");
.nont("Decl")
.nont("Block")
.endseq()
)),
rule("Decl",
...)
);
Java 8 lambdas assigning to functional interfaces
Producer<String> x = () -> "beep";
x = () -> x.apply() + x.apply();
System.out.println(x.apply());
Upvotes: 0
Reputation: 2884
Like AnthonyJClink said, you can't. But.. you can (kinda) shorten your instantiation code by not using the new
keyword if you instantiate your instance in static method of your class. For example:
public class MyClass {
private MyClass(){
}
public static MyClass create(){
return new MyClass();
}
public static void main(String[] args) {
MyClass instance = MyClass.create(); // Add parameters as needed
}
}
It reminds me of methods like int b = Integer.parseInt("444");
It makes your code more readable in some cases. It really depends on your needs. This public static instantiation is also often used with singletons getInstance()
methods.
Upvotes: 1
Reputation: 1008
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.
Upvotes: 4