简体   繁体   English

Java中对象类的继承

[英]Inheritance of Object Class in Java

While i was reading java book, i came across " Every class extends class Object "...but if want a class B to extend class A.....but Class B will be now having multiple inheritance,one from Object class and one from Class A.How the conflict is resolved. 当我读Java书时,我遇到了“ 每个类扩展类对象 ”...但是如果想要一个类B来扩展类A ......但是B类现在将具有多个继承,一个来自Object类和一个来自A类。如何解决冲突。 Can anyone explain? 谁能解释一下?

Its multi-level inheritance, not multiple: 它的多级继承,而不是多个:

class A extends Object A类扩展了Object

class B extends A B级扩展A

there is no conflict.. take a look at this structure 没有冲突..看看这个结构

  • animal 动物
    • bird
      • sparrow 麻雀
      • parrot 鹦鹉
    • dog
      • poodle 狮子狗
    • cat

the parrot class gets all attributes/methods of its super-class bird and from its super-class animal. 鹦鹉类获得其超类鸟类及其超级动物的所有属性/方法。 this is called multiple inheritance. 这称为多重继承。

You get traits from your parents right? 你从父母那里得到了什么特质吗? You also get traits from their parents also. 你也从父母那里得到了特质。

ClassB extends from ClassA which also extends from Object. ClassB扩展自ClassA,ClassA也从Object扩展。 Therefore ClassB extends Object indirectly, through classA 因此,ClassB通过classA间接扩展Object

"Every class extends class Object" just means if you don't specify the parent class, it takes on Object as the parent class “每个类扩展类对象”只是意味着如果不指定父类,它将Object作为父类

First of all, Object class is the super/base/parent class of every class including user-defined classes. 首先, Object class是每个类的超级/基类/父类,包括用户定义的类。

So even if we don't mention it explicitly, the user-defined classes extends Object class by default. 因此,即使我们没有明确提及它,用户定义的类默认扩展Object类。

Morevoer, Object class implements a set of methods and variables which are common to all the objects being created in the application. Morevoer,Object类实现了一组方法和变量,这些方法和变量对应用程序中创建的所有对象都是通用的。 This is the main reason why we have Object class as a base class for all the other classes. 这是我们将Object类作为所有其他类的基类的主要原因。

For eg: 例如:

hashCode() - this method creates a unique identity for each of the object being created in JVM. hashCode() - 此方法为在JVM中创建的每个对象创建唯一标识。

The book was trying to explain that every class is either a direct or indirect subclass of Object . 本书试图解释每个类都是Object的直接或间接子类。 Among other things, this means that every class inherits the public methods of Object : toString() , hashcode() , wait() , etc. It also means that whatever class variable a happens to be, you can always assign a to a variable of class Object . 别的不说,这意味着每一个类继承的公共方法ObjecttoString() hashcode()wait()等,这也意味着,无论类变量a恰好是,你总是可以分配a给一个变量类Object

There is no such thing as multiple inheritance in Java. Java中没有多重继承这样的东西。 The closest Java comes to that is interfaces, which is a whole subject in itself. 最接近的Java是接口,它本身就是一个完整的主题。

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

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