Java-12.2 Class Object (4)-Generalization
In this section, we will discuss the generalization of Class objects.
1. Why do we need generalization?
You can check the type of the code during compilation. You do not need to wait for the runtime to check the type.
2. Example
package com.ray.ch12;public class Test {public static void main(String[] args) {try {Class AClass1 = Class.forName(com.ray.ch12.A);AClass1 = B.class;Class AClass2 = (Class) Class.forName(com.ray.ch12.A);// AClass2 = B.class;//error} catch (ClassNotFoundException e) {e.printStackTrace();}}}class A {}class B {}
In the above example, let's take a look at the intermediate code. B. class can be assigned to AClass1, but when we generalize AClass2, B. class cannot be assigned to AClass2.
However, when Class. forName is used, we do not know the type. Therefore, the wildcard "?" is used.
3. wildcard "?"
package com.ray.ch12;public class Test {public static void main(String[] args) {try {Class
AClass1 = Class.forName(com.ray.ch12.A);} catch (ClassNotFoundException e) {e.printStackTrace();}}}class A {}
Use wildcards to make the code safer without warning.
In addition, wildcard characters can be used with extend to define the range of the type in a single interval.
package com.ray.ch12;public class Test {public static void main(String[] args) {try {Class
AClass1 = (Class
) Class.forName(com.ray.ch12.Sub);} catch (ClassNotFoundException e) {e.printStackTrace();}}}class Father {}class Sub extends Father {}
Generalization is mainly used to detect the type during compilation, and you do not need to know the problem at runtime.
Summary: This section describes the causes, usage, and wildcard characters of generalization.
This chapter is here. Thank you.