为什么要创建具有父类类型的变量 [英] Why can I create an variable with type of parent class

查看:69
本文介绍了为什么要创建具有父类类型的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我上这些课时:

public class Master{

    public String test(){
        return "I am the master object";
    }

    public String boeh(){
        return "Only inside master";
    }

}


public class Slave extends Master{

    public String test(){
        return "I am the slave object";
    }

    public String mehh(){
        return "Only insde slave";
    }

}

我知道我可以这样做: Master jedi = new Slave()(因为Slave是Master的子类型).

I know I can do this: Master jedi = new Slave() (because Slave is a child type of Master).

并且因为我可以...为什么当变量设置为Master时,为什么得到我是从属对象" .而且我得到了Slave.test()的结果,但是无法访问Slave.mehh().

And because I can... Why do I get "I am the slave object" while the variable is set to Master. And I get the result of Slave.test() but can't access Slave.mehh().

那么当变量被忽略时赋予它类型的原因是什么呢?或者换句话说,当大师绝地实际上是奴隶绝地时,它必须声明什么功能?

So whats the reason to give a variable a type when its ignored this why? Or in other words when Master jedi is actually Slave jedi what function does it has to declare Master?

推荐答案

这称为多态性(实际上,这是我们使用面向对象编程的主要原因之一).它允许您从基本类型变量调用不同的方法(在相同的签名下),而无需事先知道所包含对象的类型.因此,这使您可以拥有更多的抽象代码(该代码不紧密依赖于其各个部分的确切实现).

This is called polymorphism (and it is, in fact, one of the main reasons why we use object-oriented programming). It allows you to call different methods (under the same signature) from a base type variable without knowing the type of the contained objects beforehand. So this allows you to have more abstracted code (code that doesn't closely depend on the exact implementations of its parts).

如果希望基于运行时类型(它们的实际类型)动态分派方法,则可以使用实例方法.如果希望基于编译时类型(已将其分配给变量的类型)以静态方式分派方法,则可以改用静态方法.

If you want the methods to be dispatched dynamically, based on their runtime type (their actual type), you use instance methods. If you want the methods to be statically dispatched based on their compile-time type (the type of the variable you have assigned them to), you can use static methods instead.

这篇关于为什么要创建具有父类类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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