java - 超类方法和子类方法
问题描述
请帮助我了解此代码,谢谢!
class Parent {
int num = 4;
protected void foo() {
System.out.println("foo() of Parent");
}
static protected void bar() {
System.out.println("bar() of Parent");
}
}
class Child extends Parent {
int num = 5;
protected void foo() {
System.out.println("foo() of Child");
}
static protected void bar() {
System.out.println("bar() of Child");
}
}
public class Test {
public static void main(String[] args) {
Parent f1 = new Parent();
System.out.println(f1.num);
Parent f2 = new Child();
System.out.println(f2.num);
Child c = new Child();
System.out.println(c.num);
f1.foo();
f2.foo();
c.foo();
f1.bar();
f2.bar();
c.bar();
}
}
输出如下:
4
4
5
foo() of Parent
foo() of Child
foo() of Child
bar() of Parent
bar() of Parent
bar() of Child
你能告诉我 Person f2=new Child() 是否是多态性吗?如果是这样,为什么'f2.num'的输出是 4,而 'f2.foo()' 是 'foo() of Child'。我认为这与超类的静态bar()有关。请告诉我原理,非常感谢。
解决方案
是的,Person f2=new Child()
是一个Runtime Polymorphism。你对f2.num'
is 4的输出是绝对正确的,但是f2.foo()
is foo() of Child
。由于静态成员被继承到子类,但有一些限制:
- 您可以覆盖它们
bar()
如果您在子类中重新定义了一个方法,那么父类的继承方法 ( ) 将被隐藏
因此,当您使用正常过程运行时多态性f2
的引用创建对象时(将子对象与父对象绑定)但是当您重新定义该方法时,父方法被隐藏并且子类方法被映射到该语句Parent class
bar()
bar()
f2.bar()
推荐阅读
- python - 在熊猫数据框中使用包含 jpg 文件的最佳方法?
- latex - tlmgr 无法再访问 ctan 存储库
- arduino - 如何将 0 值发送到 ESP8266/arduino
- vba - VBA 代码 32 位到 64 位
- pyspark - 未能在 Delta 表中保存结构字段
- php - php:如何使用 simplexml_load_file 解析节点名称中包含“:”的 XML?
- python - 尝试使用 pip 在 Python 中安装 ssl 库时出现语法错误
- python - PySpark/python- 我尝试使用 for 循环,但它返回空数据帧。我该如何解决?
- c# - C# - 数学/逻辑 - 检查哪个值更接近
- neo4j - Neo4J 数据库性能