Java is a strongly typed language.
Standard conversions and automatic promotions are applied to primitive types.
Type compatibility is strictly enforced.
Normally, a reference variable from one class cannot reference an object from another class.
Even if classes X and Y are structurally the same, it is not possible to assign a reference of X to an object of Y because the types are different.
In general, an object reference variable can only reference objects of its type.
The exception to type imposition is that the reference variable of a superclass can reference objects of any subclass derived from that superclass.
As Y is derived from X, x2 is allowed to receive a reference to an object of Y.
The type of the reference variable, not the type of the object it references, determines the members that can be accessed.
When a reference to a subclass object is assigned to a superclass variable, it is only possible to access the members defined by the superclass.
In the example, x2 cannot access member b of Y, as class X is unaware of the members added by the subclass.
Subclass references assigned to superclass variables are common, especially when calling constructors in class hierarchies.
Subclasses can benefit from constructors that take an object from the superclass as a parameter, allowing the creation of copies of objects.
In this program, t2 is constructed from t1 and is therefore identical.
Attention in this Triangle builder:
// Constructs one object from another.
Triangle(Triangle ob) {
super(ob); // passes the object to the constructor of TwoDShape
style = ob.style;
}
It receives an object of type Triangle and passes it (through super) to this TwoDShape constructor:
//Constructs one object from another.
TwoDShape(TwoDShape ob) {
width = ob.width;
height = ob.height;
}
The TwoDShape() constructor expects to receive an object of type TwoDShape.
The constructor of the Triangle() subclass passes it an object of type Triangle.
This works because a reference from a superclass, like TwoDShape, can reference an object from a subclass, like Triangle.
It is acceptable to pass a reference from an object of a derived class to a constructor of the superclass.
The superclass constructor, TwoDShape(), only initializes members belonging to the TwoDShape class, regardless of additional members of the Triangle subclass.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3