简体   繁体   English

Object Class(多态、铸造)

[英]Object Class (polymorphism, casting)

I'm a newbie learning Java and I just read about Object class as a superclass of all objects.我是一个学习 Java 的新手,我刚刚读到 Object class 作为所有对象的超类。 I wonder now, if I want to create more classes (according to polymorphism rules) and the Object class is supposed to be "on top", can I create it or should I just treat it as "default"?我现在想知道,如果我想创建更多的类(根据多态性规则)并且 Object class 应该在“顶部”,我可以创建它还是应该将其视为“默认”?

The Object class in Java is the root of all classes. Object中的Object class是所有类的根。

Every class you create implicitly extends Object .您创建的每个 class 都会隐式extends Object Though those class definitions are equal:尽管这些 class 定义是相同的:

class MyClass { }
class MyClass extends Object { }

The extends Object part is done for you automatically by the compiler. extends Object部分由编译器自动为您完成。

If you have a class hierarchy, then the first class in this hierarchy is always (implicitly) Object :如果你有一个 class 层次结构,那么这个层次结构中的第一个 class 总是(隐含地) Object

class A { } // A will implicitly extend Object
class B extends A { } // though B is of type Object, too, because A is, too

That's the reason why you can cast everything (except for primitives) to Object :这就是为什么您可以将所有内容(基元除外)转换为Object的原因:

A a = new A(); // works
B b = new B(); // works

Object a = new A(); // works, because A implicitly extends Object
Object b = new B(); // works, because B extends A, and A extends Object, and though B extends Object, too

A a = new B(); // works, because B extends A
B b = new A(); // fails, because A does not extend B

In general you never write extends Object yourself, because it is done for you automatically by Java.通常,您永远不会自己编写extends Object ,因为它是由 Java 自动为您完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM