java父类如何引用指向子类对象

29次阅读
没有评论

共计 413 个字符,预计需要花费 2 分钟才能阅读完成。

在 Java 中,父类可以引用指向子类对象,这种特性称为多态性。具体实现方式如下:

  1. 定义一个父类和一个子类:
class Parent {public void display() {System.out.println("This is the parent class.");
    }
}

class Child extends Parent {@Override
    public void display() {System.out.println("This is the child class.");
    }
}
  1. 创建子类对象,并用父类引用指向它:
Parent parent = new Child();
parent.display();

在上面的代码中,父类 Parent 的引用 parent 指向子类 Child 的对象。当调用 display() 方法时,实际上会调用子类 Child 中的 display() 方法,因为多态性允许父类引用指向子类对象,并且调用子类重写的方法。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-05-08发表,共计413字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)