Why can a super class be initialized as a child cl

2020-06-16 02:04发布

In a nutshell, how and why is this possible:

Object obj=new MyClass();

Object is the superclass of all objects, therefore MyClass is a child class of Object. In general, in Java, Why is it possible to use the constructor of a child class in the parent class?


I understand how it could go the other way around, since the child has all the variables/methods of the parent class, so when you initialize them you are just initializing the variables specified in the parent constructor, that exist by definition in the child. The problem is, when you go the other way around, it is not necessarily true. A child can have variables the parent doesn't, so how is it possible to use the child constructor with the parent, when the parent does not even have the variables in the first place?


What uses does this feature have in development? I would think that if you want an instance of class B, you would declare it as B thing=new B(), and not A thing=new B(). This is probably my inexperience talking, so I would appreciate enlightenment on why and how a parent class can be initialized as one of its children.

8条回答
小情绪 Triste *
2楼-- · 2020-06-16 02:54

enter image description here

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class.

i.e. every Java class is an Object. This is why.

http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

The Object class, defined in the java.lang package, defines and implements behavior common to all classes—including the ones that you write. In the Java platform, many classes derive directly from Object, other classes derive from some of those classes, and so on, forming a hierarchy of classes.

查看更多
Animai°情兽
3楼-- · 2020-06-16 02:54

You have two separate things here:

  • The construction of a new instance
  • The assignment of that instance to a variable

Since your instance of MyClass is also an instance of Object, this works well.

Consider the following, generic situation:

class A extends B implements C,D {
}

As your A is a B and also a C and a D and an Object, once you created an instance, you can (directly or indirectly) assign it to variables of all those types:

A a = new A();
B b = a;
C c = a;
D d = a;
Object o = a;

Your view on the fields or methods is limited by the type of the variable (i.E. as variable of type C, you only see the methods declared by C). Nevertheless, your instance is always of the type you instanciated using the constructor, regardless of the variable type.

查看更多
登录 后发表回答