The examples in this article describe the concept of java object transformation and are shared with you for your reference. The specific methods are as follows:
Notes on object casting (casting) are as follows:
1. A reference type variable of a base class can "point" to an object of its subclass.
2. A reference to a base class cannot access newly added members (properties and methods) of its subclass object.
3. You can use the reference variable instanceof class name to determine whether the object "pointed to" by the reference variable belongs to this class or a subclass of this class.
4. Objects of subclasses can be used as objects of base class, which is called upcasting, and vice versa is called 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 running results are shown in the figure below:
I hope this article will be helpful to everyone’s Java programming design.