Assignment between Java Neutron class and base class variable

Source: Internet
Author: User
Tags java throws

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.