当我可以通过引用子类来访问所有方法时,为什么还要引用基类?

Why should I reference the base class when I can access all the methods just as well by referencing the subclass?(当我可以通过引用子类来访问所有方法时,为什么还要引用基类?)

本文介绍了当我可以通过引用子类来访问所有方法时,为什么还要引用基类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Java 概念.我对java继承概念有疑问.在继承中,我们可以将子类实例分配给基类引用并且我们只能访问基类函数.我们可以将继承层次结构中的任何子类实例分配给基类引用.对于分配给特定基类引用的实例类型,我们只能访问基类函数,我没有发现任何区别.

I am learning java concepts. I got a doubt in java inheritance concept. In inheritance we can assign subclass instance to a base class reference and with that we can access only base class function. and we can assign any subclass instance in the hierarchy of inheritance to base class reference.For an type of instance assigning to a particular base class reference we can access only base class functions and i didn't find any difference.

谁能给我一个实际的概念为什么我们必须将子类实例分配给基类引用?有什么必要这样做?相反,我们可以从仅知道子类引用的子类引用中访问那些基类函数.

Can any one give me actual concept why we have to assign subclass instances to base class references? what is the need to do that? Instead we can access those base class functions from subclass reference only know.

通过考虑特定的基类和层次结构中的许多子类来解释.

Explain by considering a particular base class and many subclasses in the hierarchy.

推荐答案

您可能想要这样做的原因是为了创建更健壮的设计.以 Java 中的集合框架为例.你有一个 List 接口,然后你有两个实现,ArrayList 和 LinkedList.

The reason why you may want to do this is to create more robust designs. Take for example the Collections Framework in Java. You have a List interface and then you have two implementations, ArrayList and LinkedList.

您可以编写程序以专门使用 LinkedList 或专门使用 ArrayList.但是,您的程序随后取决于这些特定的实现.

You can write your program to use a LinkedList specifically or an ArrayList specifically. However, your program then depends on those specific implementations.

如果您将程序编写为依赖于超类型 List,那么您的程序可以适用于任一 List 实现.假设您想编写一个对 List 执行某些操作的方法,并且您编写了以下代码:

If you write your program to depend on the super type, List, instead then your program can work for either of the List implementations. Lets say you want to write a method that does something to a List and you wrote this:

  public void doSomething(ArrayList a){}

这个方法只能用 ArrayList 调用,不能用 LinkedList 调用.假设您想对 LinkedList 做同样的事情?然后你复制你的代码吗?没有.

This method can only be called with an ArrayList, not a LinkedList. Suppose that you wanted to do the same thing with a LinkedList? Do you then duplicate your code? No.

  public void doSomething(List l){}

将能够接受任一类型的列表.

Will be able to accept either type of List.

这背后的原理是程序到接口而不是实现.即List定义了所有列表的功能.

The principle behind this is program to an interface not an implementation. That is, List defines the functions of ALL lists.

有很多这种用法的例子.

There are many many examples of this usage.

这篇关于当我可以通过引用子类来访问所有方法时,为什么还要引用基类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:当我可以通过引用子类来访问所有方法时,为什么还要引用基类?

基础教程推荐