java - 当我们对对象进行类型转换时会发生什么。?

标签 java oop inheritance

我有两个类,如下所示。

    class One {
      void disp() {
         System.out.println("Super class disp() method");
      }

      void show() {
        System.out.println("Super class show() method");
      }
    }

    class Two exntends One{
      void disp(){
          System.out.println("Sub class disp() method");    
      }
    }

class TestInheritance {
   public static void main(String args[]) {
     One o = new Two();
     o.disp();

     Two t = (Two) new One();
   }
}
  1. 当我们将子类对象转换为父类(super class)对象时,内存方面会发生什么?

    One o = new Two();
    
  2. 当我们将父类(super class)对象转换为子类对象时,内存方面会发生什么?

    Two t = (Two) new One();
    

最佳答案

What happens in terms of memory when we convert sub class object to super class object.?

One o = new Two();

发生的情况是创建了一个 Two 实例,并将引用分配给 o

这不会以任何方式更改 Two 实例。它没有“转换”。它仍然是一个 Two

What happens in terms of memory when we convert super class object to sub class object.?

Two t = (Two) new One();

发生的情况是创建了一个 One 实例,并测试其类型以查看 One 是否为 Two。因为它不是...立即抛出 ClassCastException

(之后,刚刚分配的 One 实例将无法访问,并且会成为垃圾回收的候选对象......下次 GC 运行时。)

事实上,你可能是这个意思:

One o = new Two();
Two t = (Two) o;

在这种情况下发生的情况是,第一条语句创建了一个 Two 实例并将其引用分配给 o。然后在第二条语句中,测试o所引用的对象的类型,看它是否“is-a”Two。因为它是...,然后将引用分配给 t

再一次,这不会以任何方式更改 Two 实例。它没有“转换”。它仍然是一个 Two


Can you give some detail about how the memory will be allocated.? I mean "when Two class object is created, memory will be allocated for Two's members and One's members as well (reason being One is super class for Two)" and will be referred by 't'.

没错

When we do "One o = new Two()", we will be able to access only One class members.

没错。

When we are converting like this (sub class object pointed by super class reference), what exactly happens internally..?

所有发生的事情是编译器和运行时“忘记”了 o 实际上引用了一个 Two,并且只允许您使用引用来访问字段/One 类定义的方法。

关于java - 当我们对对象进行类型转换时会发生什么。?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23362900/

相关文章:

C#:DataTable逐行转换

java - 将功能注入(inject)两个没有公共(public)父类(super class)的类

c++ - 在基类中设置一些值后,可以设置指向派生类的指针吗?

java - 如何向 netbeans 中的现有项目添加新类?

java - 分解循环

C# 隐藏继承成员

java - 对象和数据结构有什么区别?

JavaScript 类继承 - 填充方法不起作用

java - 在构造函数中使用 Arraylist

java - Hibernate:在不同模块中启用首次提交获胜和最后提交获胜