1.当子类和父类中有相同的成员属性的时候
public classDemo {public static voidmain(String[] args) {
Father son=newSon();
System.out.println(son.num);
}
}classFather{public int num=4;
}classSon extends Father{int sum=5;
}
执行结果是 4
多态调用该变量时:
编译时期:参考的是引用型变量所属的类中是否有被调用的成员变量。/如果/没有该变量,编译失败。
运行时期:也是调用引用型变量所属的类中的成员变量。
因为他指向的父类型的引用,创建的子类型,这是只能看到父类型里面有的东西,隐藏了子类型里面具体的内容
2.当父类和子类中拥有同名的非静态方法的时候
public classDemo {public static voidmain(String[] args) {
Father son=newSon();
son.show();
}
}classFather{voidshow() {
System.out.println("father method is called");
}
}classSon extends Father{voidshow() {
System.out.println("son method is called");
}
}
编译时期,参考左边,如果没有该方法,则编译失败。
运行时期,参考右边的对象所属的类。
3.当子类和父类里面拥有同名的静态函数的时候
public classDemo {public static voidmain(String[] args) {
Father son=newSon();
son.show();
}
}classFather{static voidshow() {
System.out.println("father method is called");
}
}classSon extends Father{static voidshow() {
System.out.println("son method is called");
}
}
因为是静态函数。 所以已经和对象没有关系 只和调用者有关系
所以编译和运行的结果都参考左边
静态的属性或者方法是很少使用多态来调用的,只会出现在面试题中。
所以多态指的就是对象的多态
对于成员函数和成员属性是动态绑定到对象上
对于静态函数和静态属性是静态绑定到类上的,不绑定到对象上 这是根本因为它在内存中存储的区域不同
方法区:构造函数,非静态方法,构造代码块
方法区中的静态方法区:静态函数,静态代码块