This article describes the concept of the transformation of Java objects, shared for everyone to reference. The specific methods are as follows:
Object Transformation (casting) The following considerations:
1, a reference type variable of a base class can "point to" the object of its subclass.
2, a reference to a base class cannot access the newly added members (properties and methods) of its subclass object.
3, you can use the reference variable instanceof class name to determine whether the reference variable refers to an object belonging to that class or subclass of that class.
4, the subclass object can be used as the object of the base class to use called upward transition (upcasting), and vice versa becomes downward transition (downcasting).
The specific implementation code is as follows:
public class testcasting{public static void Main (String args[]) {Animal Animal = new Animal ("name");
Cat cat = new Cat ("CatName", "Bluecolor");
Dog Dog = new Dog ("Dogname", "Yellowcolor");
SYSTEM.OUT.PRINTLN (animal instanceof animal);
System.out.println (cat instanceof Animal);
System.out.println (dog instanceof Animal); SYSTEM.OUT.PRINTLN (animal instanceof cat);
Error animal = new Dog ("Doganimal", "Dogcolor");
System.out.println (Animal.name); System.out.println (Animal.forcolor);
Error SYSTEM.OUT.PRINTLN (animal instanceof animal);
SYSTEM.OUT.PRINTLN (animal instanceof Dog);
Dog D1 = (Dog) animal;
System.out.println (D1.forcolor);
Class animal{public String name;
Public Animal (String name) {this.name = name;
} class Cat extends animal{public String Eyecolor;
Public Cat (string name, String eyecolor) {super (name);
This.eyecolor = Eyecolor; } class Dog extends animal{public StRing Forcolor;
Public Dog (string name, String forcolor) {super (name);
This.forcolor = Forcolor;
}
}
The results of the operation are shown in the following illustration:
I hope this article will help you with your Java programming.