java enum 初始化_OnJava8_初始化和清理

Java对象初始化通过构造器,清理通过垃圾收集器(Garbage Collector, GC)

构造器

无参构造函器,有参构造器

如果创建一个类,没有自定义构造器,编译器会自动创建一个无参构造器

方法重载

函数名相同,参数个数或者参数类型不同,也可参数顺序不同(不推荐)

this关键字

this可以表示当前对象的引用,不能用于静态方法(静态方法与对象无关)

public class Leaf{

int i = 0;

Leaf increment(){

this.i++;

return this;

}

void print(){

System.out.println("i = "+i);

}

public static void main(String [] args){

Leaf x = new Leaf();

x.increment().increment().increment.print();

}

}

this 关键字在向其他方法传递当前对象时也很有用:

class Person {

public void eat(Apple apple) {

Apple peeled = apple.getPeeled();

System.out.println("Yummy");

}

}

public class Peeler {

static Apple peel(Apple apple) {

// ... remove peel

return apple; // Peeled

}

}

public class Apple {

Apple getPeeled() {

return Peeler.peel(this);

}

}

public class PassingThis {

public static void main(String[] args) {

new Person().eat(new Apple());

}

}

this 在构造器中如果被传入一个参数列表,则是通过最直接的方式显示得调用匹配参数列表得构造器

public class Flower {

private int preCount = 0;

String s = "initial val

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值