gpt4 book ai didi

java - 内存如何分配以及什么存储在哪里? : Java Inheritance

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:02 26 4
gpt4 key购买 nike

您好,我有一个关于 Java 继承的具体问题。以下是我的代码

class Parent{
int x = 5;
public void method(){
System.out.println("Parent"+ x);
}
}
public class Child extends Parent{
int x = 4;
public void method(){
System.out.println("Child"+ x);
}
public static void main(String[] args){
Parent p = new Child();
System.out.println(((Child) p).x);
System.out.println(p.x);
}
}

现在我的问题是运行这个程序时幕后实际发生了什么。

  • 什么会被继承?
  • 内存位置在哪里?
  • 为什么第一个 syso 给出 4,第二个给出 5?(这个我能够在某种程度上理解,但澄清以上两个将有所帮助理解得更清楚)

请指导

最佳答案

在 Java 中,没有没有变量重写,只有方法重写

    System.out.println(((Child) p).x);

该行告诉 p 指向 Child 并获取该 x 变量。

System.out.println(p.x); 行告诉打印 Parentx

关于java - 内存如何分配以及什么存储在哪里? : Java Inheritance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20243422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com