Java---Casting (object transformation)

Source: Internet
Author: User

1. A reference-type variable of a base class can "point to" its child class object

2. A reference to a base class does not have access to the newly added members (properties and methods) of its child class object

3. You can use the reference variable instanceof class name to determine whether the object that the reference variable "points to" belongs to the class or subclass of the class.

4. A subclass object can be used as an object of a base class to use called up Transformation (upcasting), which is called downward transformation (downcasting).

public class Testcasting {

public void F (Animal a) {
System.out.println ("Name:" + a.name);
if (a instanceof Dog) {
Dog d = (dog) A;
System.out.println ("Furcolor:" + d.furcolor);
}
}//If the passed parameter is an object of the animal class, only name is printed, and if the passed-in parameter is the subclass dog object, you also need to print the Furcolor


public static void Main (string[] args) {
Animal a=new Animal ("Animal");
Dog D=new Dog ("Carl", "Black");

System.out.println (d instanceof Animal); //true
System.out.println (a instanceof Dog);//false
System.out.println (a instanceof Animal);//true

Animal a1=new Dog ("Dog1", "white");
System.out.println ("A1.name:" +a1.name+ ", A1.furcolor:" +a1.furcolor);// error, base class object A1 cannot access the newly added members of the subclass Furcolor
Dog d1= (dog) a1;// can cast a base class object A1 to a subclass object D1
System.out.println ("D1.name:" +d1.name+ ", D1.furcolor:" +d1.furcolor);

Testcasting test=new testcasting ();

Test.f (a);//name:animal

TEST.F (d);//name:carl Furcolor:black

}

}

Class animal{
String name;
Public Animal (String name) {
This.name=name;
}
}

Class Dog extends animal{
String Furcolor;
Public Dog (String name,string furcolor) {
Super (name);
This.furcolor=furcolor;
}
}

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.