Java-12.2 Class Object (4)-Generalization

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.