[JAVA] Downcast story (memories)

What is downcast

Storing a superclass object in a subclass object.

Downcast failure

I should check if the instance can be assigned using instance of, but I thought that I should understand without checking, so I decided to write my own interpretation as a memorandum.

When I actually make the code ...

NG pattern (downcast)
public class Human {
  public void speak (){
    System.out.println("a-I-U-E-O");
  }
}
public class Men extends Human {
  public void speak (){
    System.out.println("Kakikukeko");
  }
}
public class Main {
  public static void main void (String [] args){
    Human h = new Human();
    Men M = (Men) h;
  }
}

In this case, Human does not know the contents of Men and cannot downcast.

However, in the following cases (edit Main class)

public class Main {
  public static void main void (String [] args){
    Human h = new Men();
    Man m = (Man) h;
  }
}

Men know what Human is, so they can downcast.

Recommended Posts

Downcast story (memories)
Range story
Upcast / Downcast