Assignment between Java Neutron class and base class variable
A subclass object can be assigned directly to a base class variable.
To assign a base class object to a subclass object variable, you must perform a type conversion,
Its syntax is:
Sub-class object variable = (subclass name) base class object name;
Nor can it be converted into chaos. If the type conversion fails, Java throws the following exception:
ClassCastException
Package Yanzheng;
class mammal{}
class Dog extends Mammal {}
class Cat extends mammal{}
Public class Testcast
{
Public Static void Main (String args[])
{
< /span>m
< /span>d new dog ();
< /span>c new cat ();
m = D ;
D=m;
D = (Dog) m ;
D=c;
C = (Cat) m ;
}
}
The first one: correct. Subclasses can assign values to base class objects.
Second: error. Cast m of parent class to subclass D
The third one: The fifth one refers to the conclusions from the beginning.
Fourth one: No. Although they all inherit from the same parent class, they are still two different subclasses, and two different subclasses cannot be assigned a value.
Assignment between Java Neutron class and base class variable