方法的重载
-
方法的重载是指一个类中可以定义有相同的名字,但参数(个数、类型、顺序)不同的多个方法,调用时,会根据不同的参数表选择不同的方法。
-
举例Person类
void out() { System.out.println("out"); } void out(String t) { System.out.println("out" + t); } public class Test() { public static void main(String args[]) { Person p = new Person(); p.out(); p.out("hello"); } }
-
构造方法的重载
- 和普通方法一样,构造方法也可以重载
class Person {
Person() {
id = 100;
age = 20;
}
Person(int pid) {
id = pid;
age = 30;
}
Person(int pid, int page) {
id = pid;
age = page;
}
}
this关键字
- 在类的方法定义中使用的this关键字代表使用该方法的对象的引用。
- 当必须指出当前使用方法的对象是谁时使用this。
- 有时使用this可以处理方法中成员变量和参数重名的情况。
- this可以看作是一个变量,它的值是当前对象的引用。
public class Leaf {
int i = 0;
Leaf(int i) {
this.i = i;
}
Leaf increament() {
i ++;
return this;
}
void print() {
System.out.println("i = " + i);
}
public static void main(String[] args) {
Leaf leaf = new Leaf(100);
leaf.increament().increament().print();
}
}
执行Leaf leaf = new Leaf(100);
后(1消失),内存空间如图
leaf.increament().increament().print();
执行完后内存如图