Java Learning Note (21): Type conversions and instanceof keywords

Source: Internet
Author: User

basic Data type conversions :

Automatic type conversion: Assigning large types of data to large types of variables (where size refers to the range of capacity)

1 byte b = n;  // byte is a byte 2 int  i = b;   // int is four bytes

Coercion type conversions: assigning large types of data to small types of variables

1  Short S  = (short) i; I is int type four bytes, S is short type two bytes

Reference type conversions:

Reference types are large and small, referring to the relationship of the parent class and the child class

Automatic type conversion: Assigning a Class object to a parent class variable (polymorphic)

1 New Dog ();

Coercion type conversion: Assigning a parent class type object to a subclass object

1 New Dog (); 2 Dog d = (dog) A;

Instanceof Operator:

Determine if an object is an instance of a class

1 Boolean instanceof // determines whether the A object is an instance of Class B, and if so, returns True

Example 1:

1  Public voidFeed (Animal a)2 {3 a.eat ();4     if(AinstanceofDOG)//If animal A is a dog class object5     {6Dog d = (dog) A;//turn animal a strong into dog class7D.watch ();//housekeeping methods for executing the dog class8     }            9     Else if(AinstanceofCat)//If animal A is a cat class objectTen     { OneCat C = (cat) A;//turn animal a strong into cat class AC.catchmouse ();//perform cat-like mouse-catching methods -     }   -}

Example 2:

1Object obj = "ABC";//Polymorphic , assigning a String object to the type of object2System.out.println (objinstanceofObject);//true3System.out.println (objinstanceofObject);//true4System.out.println (Obj.getclass ());//get the True type of an object5System.out.println (obj.getclass () = = String.class);//true6System.out.println (obj.getclass () = = Object.class);//false

Run output:

:

Java Learning Note (21): Type conversions and instanceof keywords

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.