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