Java中能否不使用括号创建对象?自定义类可采用特殊实例化语法吗?
Great question! Let's break this down clearly:
That bracket-based instantiation syntax (new Type[dim1][dim2]...) is exclusive to array objects in Java. Custom classes cannot use this alternative instantiation pattern—they must follow the standard new ClassName(...) syntax for object creation.
Why is this the case?
Arrays are a special built-in object type in Java, with dedicated language syntax support defined in the Java Language Specification. The JVM treats arrays differently under the hood (for example, every array type has an implicit class like [Ljava.lang.String; for String[]), which allows this unique initialization style.
For custom classes, instantiation always requires calling a constructor via the new ClassName(...) format. The parentheses hold any arguments required by the constructor (even empty parentheses for a no-arg constructor).
Example: Custom Class Instantiation
Here's how you must instantiate a custom class, vs. what won't work:
// A simple custom class public class User { private String name; // No-arg constructor public User() {} // Parameterized constructor public User(String name) { this.name = name; } } // Valid instantiation User emptyUser = new User(); User namedUser = new User("Alice"); // Invalid! Custom classes can't use bracket syntax // User userArray = new User[5]; // Compile-time error
If you need "batch" custom objects
If you want to create multiple instances of a custom class (similar to an array), you'll need to either:
- Use an array of the custom class type (which still follows standard array syntax):
User[] userArray = new User[5]; // Creates an array of User references (all null initially) // Then initialize each element manually userArray[0] = new User("Bob"); - Or use a collection like
ArrayListfor easier management:List<User> userList = new ArrayList<>(); for (int i = 0; i < 5; i++) { userList.add(new User("User " + i)); }
内容的提问来源于stack exchange,提问作者Mustafa Enes Batur

