public class MyMultiField {
public static void main(String[] args) {
//使用多态的写法,父类引用指向子类对象
Fu fu = new Zi();
System.out.println(fu.num);//父:10
// System.out.println(fu.age);//错误写法!
System.out.println("===============");
fu.method();//子类没有覆盖重写,就是父:10
fu.method();//子类覆盖重写,就是子:20
}
}
public class Fu {
int num = 10;
public void method(){
System.out.println(num);
}
}
public class Zi extends Fu{
int num = 20;
int age = 16;
@Override
public void method() {
System.out.println(num);
}
}
public class DemoMultiMethod {
public static void main(String[] args) {
Fu fu = new Zi();
fu.method();//new的是子优先用子
fu.methodFu();//子类没有,父类有,向上找到父类。
//编译看左边,左边是Fu,没有methodZi方法,所以编译报错。
//fu.methodZi();//错误写法!
}
}
public class Fu {
public void method(){
System.out.println("父类方法");
}
public void methodFu(){
System.out.println("父类特有方法");
}
}
public class Zi extends Fu{
@Override
public void method() {
System.out.println("子类方法");
}
public void methodZi(){
System.out.println("子类特有方法");
}
}