繁体   English   中英

如何分配内存,什么存储在哪里? :Java继承

[英]How memory gets allocated and what gets stored where? : Java Inheritance

嗨,我有一个关于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,第二个sys给出5?(我在某种程度上可以理解,但是对上述两个进行澄清将有助于更清楚地理解它)

请指导

在Java中, 没有变量覆盖 ,只有方法覆盖

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

那条线将p告诉Child并获得x变量。

System.out.println(px); 告诉打印Parentx

它全部与Java inheritanceoverriding 父类中的method()将被子方法覆盖。

System.out.println(((Child) p).x);// here you are invoking child 

然后,您将获得孩子的属性。

接下来就是Java多态性。

 ((Child) p).x // invoking object type, x=4 (object is child ) 

  p.x  // invoking reference type, x=5 (reference is parent)

请参考此链接 链接

继承了什么?

所有公共方法和受保护方法都在子类中继承。 字段永远不会被继承。

内存位置在哪里?

我写了一篇有关Java中对象创建过程的博客文章 我认为您会更好地理解它。

为什么第一个syso给4,第二个给5?

字段访问总是基于引用的声明类型而不是实际对象类型来解决。 因此, px将访问Parent的字段,因为p声明类型为Parent 鉴于((Child)p).x将访问Child的字段,因为您将引用p强制转换为Child ,现在考虑的声明类型为Child

在Java中,将实例化Always子类对象。 在实例化子类时,将调用超类构造函数,以便仅声明超类变量并在子类对象中分配内存。 并且默认情况下,超类的公共和受保护方法会继承到子类。 因此,总结来说,内存仅分配给子类。 您可以在本地使用JDK Java虚拟VM进行验证,以查看实例列表。

例如继承中的变量:假设内存中有两个圆圈

内圈是其中具有父实例变量的父级,外圈是其中具有子实例变量的子级。

子引用可以访问父实例变量,但反之亦然,因为父实例不了解子实例,所以反之亦然
https://i.stack.imgur.com/sR1bS.jpg
https://www.java-forums.org/new-java/96742-how-memory-allocated-during-inheritance.html

class Test1 {       
    public int gear = 10; 
    public int speed =110 ;
} 

// derived class 
class MountainBike extends Test1 
{ 
    //public int gear = 9; 
    public int speed =11 ; 
    // the MountainBike subclass adds one more field 
    //public int seatHeight;
} 

// driver class 
public class Test 
{ 
    public static void main(String args[]) 
    {           
        Test1 mb = new MountainBike(); 
        System.out.println("Hii"+mb.gear); 

        MountainBike m = new MountainBike();

        System.out.println("Hii123 "+m.gear);
    }
} 

上面的代码将输出10..10作为输出。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM