您的位置:首页 > 编程语言 > Java开发

理解java中的new

2015-06-15 19:25 387 查看
书上对new的解释

1.The new keyword is a Java operator that creates the object.

2.The new operator is followed by a call to a constructor, which initializes the new object.

3.The reference returned by the new operator does not have to be assigned to a variable

4.The new operator requires a single, postfix argument: a call to a constructor.

5.The new operator instantiates a class by allocating memory for a new object and returning a reference to
that memory

Tag:

All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default
constructor.

Object 与 Class

这个是面向对象编程时需要理解的基础知识,不懂的可以看看书籍的介绍

不过需要强调的是class是类型模板,而object是single的,说白了就是被具体化的class,不过我们在这里是要好好理解一个new到底做了什么事情,它开辟内存空间,然后返回一个ref给一个var,然后通过这个var来操作方法,而且这个对象是可变状态,可以通过ref修改其中的属性,不过有个地方初学者会忽略的是new是个instantiating的过程所以我们可以这样使用new来构建对象

Thread thread = new Thread(){
@SuppressWarnings("static-access")
@Override
public void run() {
super.run();
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ThreadTest.OSPrintln("run thread");
}
@SuppressWarnings("deprecation")
//摧毁线程但不回收资源
@Override
public void destroy() {
super.destroy();
ThreadTest.OSPrintln("destroy");
}
};

上面是我们在new时直接具体化class了,这样有好有怀,好的地方是它可具体化属性或实现抽象方法或是接口,说白了就是重造class,例如你可以添加方法,不过这都是临时,它不会影响class,不过这样写程序会使得程序变得特别臃肿,不好管理,违背了class模板的原则,不过有时这样使用会让程序变得更加~例如写接口回调时,实例化接口时

new Runnable() {
@Override
public void run() {
ThreadTest.OSPrintln("run Runnable");
}
}.run();



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: