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

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

问题描述

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

任何人都可以给我实际概念
为什么我们必须将子类实例分配给基类引用?
需要做什么?
相反,我们可以从子类引用只知道访问那些基类函数。



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

解决方案

您可能想要这样做的原因是为了创建更强大的设计。以Java中的Collections Framework为例。你有一个List接口,然后你有两个实现,ArrayList和LinkedList。



你可以编写你的程序专门使用LinkedList或ArrayList。但是,你的程序依赖于那些特定的实现。



如果你编写的程序依赖于超类型List,那么你的程序可以用于任何一个列表实现。让我们说你想写一个对List做一些事情的方法你写了这个:

  public void doSomething(ArrayList a) {} 

此方法只能使用ArrayList调用,而不能使用LinkedList调用。假设你想用LinkedList做同样的事情?那你复制你的代码了吗?否。

  public void doSomething(List l){} 

将能够接受任何类型的List。



这背后的原理是接口的程序而不是实现。也就是说,List定义了所有列表的功能。



这种用法有很多例子。


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.

解决方案

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.

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

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){}

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.

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆