本文最后更新于 78 天前
public class 分派 {
public static void main(String[] args) {
Human man = new Man();
// 重写是 虚函数的源由(invokevirtual 所以对字段无效),看实际类型 即‘后者’
man.printCode();
// man.code是不是方法,所以输出是 Human.code即3
System.out.println("code " + man.code);
// Human women = new Women();
// 重载 看编译类型 即‘前者’(对于char类型依次:char > int > long > float > double > 变长类型)
// sayHello(man);
// sayHello(women);
}
static void sayHello(Human humam) {
System.out.println("human sayHello");
}
static void sayHello(Man man) {
System.out.println("man sayHello");
}
static void sayHello(Women women) {
System.out.println("women sayHello");
}
}
class Human {
public int code = 2;
public Human() {
code = 3;
printCode();
}
void printCode() {
System.out.println("Human code " + code);
}
}
class Man extends Human {
public int code = 0;
public Man() {
code = 1;
printCode();
}
void printCode() {
System.out.println("Man code " + code);
}
}
class Women extends Human {
}
- “覆盖”私有方法
public class 分派2 {
// 声明为private,输出为 Shape
private void print() {
System.out.println("Shape");
}
public static void main(String[] args) {
分派2 s = new Derived();
s.print();
}
}
class Derived extends 分派2{
public void print() {
System.out.println("Circle");
}
}