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.
这篇关于为什么我可以创建具有父类类型的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么我可以创建具有父类类型的变量


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01