Coercion of Java Object-Oriented Polymorphism

You must pay attention to the forced transfer:

What is the real type of the object, then the minimum forced conversion can only be converted to this type.

First, let's look at a piece of code:

public class Cast extends Super_Cast2{
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		Super_Cast2 s2 = new Super_Cast2();
		Super_Cast1 s1 = s2;
		System.out.println(s2);
		Cast cast = (Cast)s1;
	}
	@Override
	public void check() {
    
    
		// TODO Auto-generated method stub
		System.out.println("Cast");
	}
}
class Super_Cast1{
    
    
	public void check() {
    
    
		System.out.println("Super_Cast1");
	}
}
class Super_Cast2 extends Super_Cast1{
    
    
	public void check() {
    
    
		System.out.println("Super_Cast2");
	}
}

Solution: Let's analyze the code, Cast inherits Super_Cast2, Super_Cast2 inherits Super_Cast1, that is, Super_Cast1>Super_Cast2>Cast. Because a child object can be regarded as a parent type, s1=s2 is a polymorphic upcast. And Cast cast = (Cast)s1 is a coercive conversion, that is, the ancestor of s1 is coerced to Cast type. Is this operation successful? Let's compile it and see the result:

tpp.Super_Cast2@15db9742
Exception in thread "main" java.lang.ClassCastException: tpp.Super_Cast2 cannot be cast to tpp.Cast
	at tpp.Cast.main(Cast.java:10)

Obviously, this won't work, why? First, let's look at the code of Super_Cast2 s2 = new Super_Cast2(). This sentence represents that Super_Cast2 created the s2 object. But there is a note in the polymorphic grammar, that is: what is the real type of the object, then the minimum forced conversion can only be converted to this type, so the Super_Cast2 class is the minimum type. But because the Super_Cast2 class is the parent class of the Cast class, the s1 that is transformed from s2 up cannot be forced to cast.

Solution:
Change Super_Cast2 s2 = new Super_Cast2() in the code to Super_Cast2 s2 = new Cast().

public class Cast extends Super_Cast2{
    
    

	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
		Super_Cast2 s2 = new Cast();
		Super_Cast1 s1 = s2;
		System.out.println(s2);
		Cast cast = (Cast)s1;
	}
	@Override
	public void check() {
    
    
		// TODO Auto-generated method stub
		System.out.println("Cast");
	}
}
class Super_Cast1{
    
    
	public void check() {
    
    
		System.out.println("Super_Cast1");
	}
}
class Super_Cast2 extends Super_Cast1{
    
    
	public void check() {
    
    
		System.out.println("Super_Cast2");
	}
}

result:

tpp.Cast@15db9742

Analysis:
Because it is now Super_Cast2 s2 = new Cast(), it means that the smallest type that s2 can be forcibly converted is Cast, and s1 that is up-transformed from s2 can be forcibly converted to cast.

Hope to bring help to the majority of Java learners, thank you all

Guess you like

Origin blog.csdn.net/qq_42039952/article/details/114937336