为什么在用作其他对象类型时必须转换类型为object的引用变量

编程入门 行业动态 更新时间:2024-10-25 10:30:49
本文介绍了为什么在用作其他对象类型时必须转换类型为object的引用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

尽管Java中的所有类都是Object类的子类,但是与其他对象类型不同,但是如果没有强制类型转换,则不能将Object类型的引用变量分配给任何其他引用类型.

Although all classes in Java are sub-classes of Object class, but different from other object types, a reference variable of type Object can't be assigned to any other reference type without a cast.

例如:

public class Inheritance { public static class Animal { public void Scream() { System.out.println("I'm an animal"); } } public static class Mammal extends Animal{ public void Scream(){ System.out.println("I'm a mammal"); } } public static class Tiger extends Mammal{ public void Scream(){ System.out.println("I'm a tiger"); } } public static void main (String[] args){ Animal tiger = new Tiger(); tiger.Scream(); //true Object tiger = new Tiger(); tiger.Scream(); //false Object tiger = new Tiger(); ((Animal) tiger).Scream(); //true } }

推荐答案

您想知道为什么我们使用显式类型转换.这就是关于继承的全部内容-

you wanna know why we use explicit type cast. this is all about Inheritance -

让我澄清一下-假设我们有两个 A类和 B类.而 B类是 A类的子类.这意味着 Class B 具有 Class A 的所有功能,这意味着 Class B 可以做 Class A 可以做的任何事情做.因此,如果

Let me clear this - Let suppose we have two class Class A and Class B. And Class B is a sub class of class A. That means Class B has all functionality of Class A, this means Class B can do anything what Class A can do. So if

A a = new B();

非常好,因为 B级可以做到 A级可以做到的事情.这里的引用变量 a 是Class A类型的,从A类的所有方法中都可以调用.现在 B (new B();)的对象具有所有 A类(作为继承)的功能,因此 A类的所有方法都是可以调用的.

is perfectly fine because Class B can do what class A can do. Here reference varaible a is of type Class A, from a all the method of Class A will be invokable.Now Object of B(new B();) has all the functionality of Class A (as Inheritance) so all method of Class A will be invokable.

如果我们扭转这种情况->

If we reverse the condition like this ->

B b =new A();

不可能,因为可能是 Class B 实现了自己的功能(方法和变量),而这些功能不在 Class A 中.但是这里引用变量的类型为 B ,所有 Class B 的功能都可以调用,但是实际对象的类型为 A ,因此出现错误将会发生.

Not possible, because may be Class B implement its own functionality(Methods and variables) which are not in Class A. But here reference variable is of type B, all the functionality of Class B will be invokable, But the actual object is of type A so Error will occur.

类对象也是如此.其他所有类都自动继承 Object 类.

Same case is with Class Object.As all the other Class automatically inherit Object Class.

所以当具有引用变量为Class Object类型的任何对象都需要显式Cast时,因为不能确定该对象包含多少功能.

so When any object having reference variable of type Class Object need explicit Cast, Because this is not sure what more or less functionality that object contain.

更多推荐

为什么在用作其他对象类型时必须转换类型为object的引用变量

本文发布于:2023-11-02 13:56:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1552585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   变量   对象   object

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!