Last Updated:

How Static Typing Works in Java

Static typing is a check of the security of program types at compile time (by analyzing the source code of the program).

Dynamic typing — checking the safety of program types at run time.

Java uses static type checking, that is, analyzing a program at compile time. The main idea of choosing this type checking approach is to check types only 1 time when compiling, thereby increasing the speed of program execution. It also allows you to detect possible errors.

Static typing in Java

Let's look at a simple example of static typing in Java. There are two classes: Alpha and Beta with methods that do something:

Take another look at the code above and tell me what will return the method? Will it be an Alfa facility or a Beta? We know what is declared in the Alfa class, and at compile time, the compiler sees that the method returns an Alfa object. But in our case, Beta inherits Alfa and call the {return this method; (get yourself back)} will still return a Beta Beta().getThis()getThis()getThis()

We've described the classes to work with, and now let's look at how it works:

The following line cannot be invoked, even if we think we are working with a Beta object:

The problem is that its original Alpha type and the compiler does not know the actual type at compile time, so it sees an object of type Alfa. Based on this, the following operations are available to us:

or let's get around the problem by casting to Beta:

Now let's try to add another class:

And let's write this line of code:

So you can write and it will even pass static type checking (for the same reason as with ), however, at runtime an exception will be thrown "", since Beta cannot be brought to Beta().getThis().doBeta();java.lang.ClassCastException: Beta cannot be cast to Omega