理解java中的new

书上对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();




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值