对方法来说:
class Base{
public Base(){
g();}
pubilc void f(){
System.out.println("Base f()");}
public void g(){
System.out.println("Base g()");}}
class Derived extends Base{
pubilc void f(){
System.out.println("Derived f()");}
public void g(){
System.out.println("Derived g()");}}
public class test{
public static void main(String[] args){
Base b=new Derived();
b.f();
b.g();}}
输出:
Derived g()
Derived f()
Derived g()
在new创建对象的时候会调用父类的构造方法,而里面执行的g()却是子类的g而不是父类的,这是由多态导致的。
public static void main(String[] args){
Fu f new Zi();
System.out.println(f.num);
f.method();
}
class Fu{
int num 10;
public void method(){
System.out.println("Fu.method");
}}
class Zi extends Fu{
int num 20;
public void method(){
System.out.println("Zi.method")}}
输出10 Zi.method
即多态运行时,成员变量的值取决于父类,方法取决于子类;
编译时,父类如果没有会报错。