今天刚学完JavaSE的构造方法,发现概述中说的构造方法是在new一个对象时调用的,但是数组的创建和类对象创建格式不一样.
比如创建一个Student类对象,格式为Student stu = new Student();这里用到了构造方法Student().
但是创建数组的格式是int[] arr = new int[3]; 我查了下很多人都说数组也属于对象,那在new一个数组的时候,有调用构造函数吗?
new一个数组的时候,没有调用构造函数,是申请内存空间
如果你用int 是不会有构造函数的,如果你用Integer也是不调用构造函数的。
说属于实例,是因为使用new
但是,说不属于实例,是因为实例引用的是内存的一个标志
对于int[] 比较特殊,在java要求不能使用动态长度
可以作为“一组变量”理解,不是实例,
这样说OK?不懂,说
那不一样,创建对象是一定会调用构造函数的
数组是jvm用c语言实现的,new一个数组,模拟构造函数分配内存
package ask;
import java.lang.reflect.*;
public class ClassDemo2 {
public static void main(String[] args) {
try {
String s = "abc";
Class a = s.getClass();
Class clsa[] = new Class[] { a }; // creating array
Constructor c = a.getConstructor(clsa); // get the constructor
System.out.println(c); // print the constructor
int[] arr = new int[] { 1, 3, 5 };
Class b = arr.getClass();
Class clsarray[] = new Class[] { b }; // creating array
Constructor cnstrctr = b.getConstructor(clsarray); // get the constructor
System.out.println(cnstrctr); // print the constructor
} catch (Exception e) {
System.out.println(e); // print exception object
}
}
}
public java.lang.String(java.lang.String)
java.lang.NoSuchMethodException: [I.<init>([I)
数组并不存在构造函数
您好,我是有问必答小助手,你的问题已经有小伙伴为您解答了问题,您看下是否解决了您的问题,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632
非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!
速戳参与调研>>>https://t.csdnimg.cn/Kf0y
说属于实例,是因为使用new
但是,说不属于实例,是因为实例引用的是内存的一个标志
对于int[] 比较特殊,在java要求不能使用动态长度
可以作为“一组变量”理解,不是实例,
这样说OK?不懂,说