[Simple Java] How is the static type check performed in Java? simplejava
The following is an explanation of static and dynamic type checks in Wikipedia:
- Static type check: the process of verifying type security based on program source code;
- Dynamic type check: the process of verifying type security during program running;
Java uses static type check to analyze programs during compilation to ensure that there are no type errors. The basic idea is not to make a type error occur during running.
The following code is an example. If you understand it, you will better understand how Java static type check works.
Sample Code
Suppose we have the following classes: A, B, and B inherit from.
class A { A me() { return this; } public void doA() { System.out.println("Do A"); }}class B extends A { public void doB() { System.out.println("Do B"); }}
First, what will be returned when new B (). me () is called? Object A or object B?
The me () method is declared to return object A, so during compilation, the compiler only knows that it returns object. However, it returns the B object during running, because B inherits the method and returns itself.
How does static type check work?
The following code line is invalid, even if the method doB () is called by the B object. The problem is that its reference type is A. In the compiler, the compiler does not know its actual type, so it is treated as.
//illegalnew B().me().doB();
Therefore, only the following code can be called:
//legalnew B().me().doA();
However, we can convert its forced type to B, as shown in the following code:
//legal((B) new B().me()).doB();
Next, we will add a class C:
class C extends A{ public void doBad() { System.out.println("Do C"); }}
Then, the following code statement will pass the static type check:
//legal((C) new B().me()).beBad();
The compiler does not know its actual type, but will throw an exception during runtime because B cannot be converted to C;
Http://www.programcreek.com/2011/12/an-example-of-java-static-type-checking/.