为什么我可以创建具有父类类型的变量

Why can I create an variable with type of parent class(为什么我可以创建具有父类类型的变量)

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

问题描述

当我有这些课程时:

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 时得到 "I am the slave object".我得到了 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.

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

本文标题为:为什么我可以创建具有父类类型的变量

基础教程推荐