The following is an explanation of static type checking and dynamic type checking from Wikipedia:
- Static type checking: The process of verifying type safety based on the source code of the program;
- Dynamic type checking: The process of verifying type safety while the program is running;
Java uses static type checking to parse the program during compilation to ensure there are no type errors. The basic idea is not to let type errors occur during run time.
The following code is an example of how a Java static type check works if you understand him.
code example
Suppose we have the following classes, a and b,b inherit a.
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 does the call to New B (). Me () return? A object or B?
The Me () method is declared to return a object, so during compilation, the compiler only knows that it returns a object A. However, it returns a B object while it is running, because B inherits the method of a and returns itself.
How does static type checking work?
The following line of code is illegal, even if the method dob () is called by the B object. The problem is that its reference type is a, and in compiling the device, the compiler does not know its true type, so it is treated as a type.
Illegalnew B (). Me (). DoB ();
Therefore, only the following code can be called:
Legalnew B (). Me (). DoA ();
However, we can convert its coercion type to B, as in the following code:
Legal ((B) New B (). Me ()). DoB ();
Next, we add a Class C:
Class C extends a{public void Dobad () { System.out.println ("Do C");} }
Then, the following code statement is checked by a static type:
Legal ((C) New B (). Me ()). Bebad ();
The compiler does not know its true type, but will throw an exception during runtime because type B cannot be converted to type C;
Link: http://www.programcreek.com/2011/12/an-example-of-java-static-type-checking/
How static type checking is done in Java