[java] The principle of forced conversion of parent class into child class in Java

The principle of forced conversion of a parent class into a subclass in Java : the reference of the parent type refers to the instance of the subclass, which can be converted into the reference of which subclass.

Example:

public class Test {

 public static void main(String[] args) {
  Person person = new Boy();
  Boy boy = (Boy) person;
  boy.eat();
 }

}

class Person {
    public void eat() {
     System.out.println("The people were eating");
    }
}

class Boy extends Person {
 public void eat() {
  System.out.println("The boy were eating");
 }
}

Print result: The boy were eating

Reason: When the Boy is instantiated, the reference address is returned to the person. At this time, the person reference actually points to Boy, so converting the person to Boy can succeed.

Define another class:

class Girl extends Person {
 public void eat() {
  System.out.println("The girl were eating");
 }
}

main方法中添加:

  Person p = new Girl();
  Boy b = (Boy)p;
  b.eat();

Prompt when running: Girl cannot be cast to Boy (can't convert girl to boy)

Reason: When the Girl is instantiated, the reference address is returned to p. At this time, the p reference actually refers to Girl. Converting p to Boy means converting Girl to Boy, which certainly cannot succeed.

In other words, the above example is that both boys and girls are humans. This is certainly true, but you must say that girls are boys.

The premise of the parent rotor class is: this parent class object is a reference to the child class object

E.g:

  Father father = (Father)son;
当这种情况时,可以用instanceof判断是否是子类类型(实际) 然后强转回去
  if(father instanceof Son)
     Son son =(Son)father;

Other than that, no.

Guess you like

Origin www.cnblogs.com/iiiiiher/p/12687642.html