本文介绍了样本样本= new sample1();在java中这个声明中的内容请在内存级别告诉。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java怀疑:



当我们使用时会发生什么情况

Java Doubt:

what happens when we use

Sample sample // this variable for Sample class



但引用 Sample1 (另一个班级)。



有人请详细说明..



我尝试过:




but referring to Sample1(another class).

Somebody please explain in flow..

What I have tried:

Sample sample = new Sample1();





在这句话中讨厌什么在java中请告诉你内存级别。



what is happing in this statement In java please tell at memory level.

推荐答案


public class Sample {
  int var1;
  int var2;
  Sample() {}
  public void method1() {}
  public void method2() {}
}



它可以在内存中表示如下:




it may be represented in memory like this:

vtable pointer<br />
var1<br />
var2





其中vtable指针指向这个方法指针数组:





where vtable pointer points to this array of pointers to methods:

<br />
0: method1 from Sample class<br />
1: method2 from Sample class





如果你有一个像这样的后代类Sample1:



If you have a descendant class Sample1 like this one:

public class Sample1 extends Sample {
  int var3;
  Sample1() {}
  @Override
  public void method1() {}
  @Override
  public void method2() {}
}



它将是在内存中表示如下:




it will be represented in memory like this:

vtable pointer<br />
var1<br />
var2<br />
var3





其中vtable指针指向这个方法指针数组:]





where vtable pointer points to this array of pointers to methods:]

0: method1 from Sample1 class<br />
1: method2 from Sample1 class





使用new创建Sample1类实例时,它将为Sample1类创建上述内存结构。当您将其分配给Sample类型的变量时:



When you create a Sample1 class instance with new, it will create the above memory structure for Sample1 class. When you assign it to a variable of Sample type:

Sample sample = new Sample1();



编译器将允许这样做,因为Sample1类可以没有问题地用作Sample类。实际上,Sample1类实例与Sample类具有相同的变量(var1,var2)并且位于相同的位置。对于Sample1类vtable,它具有与Sample类相同的签名和位置相同的方法。因此,您可以通过Sample变量安全地使用Sample1类,因为它与它兼容。我希望这个解释对你有帮助。


compiler will allow this because Sample1 class can be used as Sample class without problems. Indeed, a Sample1 class instance has the same variables (var1, var2) as the Sample class and at the same positions. As for Sample1 class vtable, it has the methods with the same signature and at the same positions as the Sample class. So you can safely work with Sample1 class through a Sample variable as it is compatible with it. I hope this explanation will help you.


这篇关于样本样本= new sample1();在java中这个声明中的内容请在内存级别告诉。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:28