Why does the declared object type matter at runtime?

In a statically typed language such as Java, from what I have learned, type declaration is essentially a way to catch compilation errors, an obvious advantage over dynamically typed languages. But, looking at the time when Java completes the binding, we get errors, such as ClassCastExceptionshowing how declared types relate somehow at runtime. But why does the declared type really matter?

For example:

public class TestClass 
{
   public static void main(String[] args) 
   {
       Animal d = new Animal();
      ((Dog)d).bark(); //ClassCastException because an Animal is not a dog, which would make sense to throw at compile-time, but not at runtime.
   }
}

class Dog extends Animal{}

class Animal
{
   void bark()
   {
       System.out.println("Woof");
   }
}

, , , . , Java cast call bark , Animal? , , , Java (.. woofs, !) , Java .

: , , . ? , , .

+4
6

, Java. Java , . , Java , - .

. , . . , (, Object ), . static duck, .

+3

Java cast call , Animal?

. , Dog Amimal Bark?

, Bark . Bark Dog, Dog.Bark; , Bark Animal, Animal.Bark.

, , .

, # , java. , #.

+5

, # . Java, .

, . , , (a checkcast bytecode), , . - , , , , , , , .

, -, :

public static void main(java.lang.String[]);
    Code:
       0: new           #2                  // class Animal
       3: dup           
       4: invokespecial #3                  // Method Animal."":()V
       7: astore_1      
       8: aload_1       
       9: checkcast     #4                  // class Dog
      12: invokevirtual #5                  // Method Dog.bark:()V
      15: return        

JLS , , :

, .

- . , : , , .

+1

Can you explain why runtime type checking has to happen in a static-typed language

, .

  • - , Animal.
  • Dserialization Dog .
+1

"main" java.lang.ClassCastException: com.example.com.example.Animal com.example.com.example.Dog      com.example.com.example.Test.main(Test.java:12)

, , ((Dog) d) " , Animal. , .

0

, . . . , .

-1

Source: https://habr.com/ru/post/1622310/


All Articles