I wrote about Java downcast in an easy-to-understand manner


This article is a continuation of "Upcast (Java) that can reduce the amount of change when the specification is changed". Therefore, some source code (Cat class, Dog class, Life_form class) etc. are listed in the "Source code" item at the bottom.

The text starts with "What is a downcast?"

Development environment

Text editor used Atom (hereinafter atom -vertion execution result)

Atom : 1.28.0 Electron: 2.0.3 Chrome : 61.0.3163.100 Node : 8.9.3

~ Below, the execution result of the command "java -version" ~

java version "1.8.0_161" Java(TM) SE Runtime Environment (build 1.8.0_161-b12) Java HotSpot(TM) 64-Bit Server VM (build 25.161-b12, mixed mode)

What is downcast

In "Upcast (Java) that can reduce the amount of change when specifications are changed", upcast was dealt with, but the opposite operation is called downcast.

But don't put it together so easily.

The upcast was a safe type conversion. Since the child class inherits from the parent class, it has all the fields and functions of the parent class. So even if you assign (upcast) a child class to an instance of the parent class, it makes sense to work fine.

But downcasting doesn't work that way. The parent class does not have its own functions in the child class. ** It would be a bit strange to declare a child class but not have the functions and fields that the child class should have. ** **

In fact, when I try to downcast, the compiler gets angry like this.

Failure example 1


public class Main{
  public static void main(String[] args){

    Cat cat = new Life_form();       //Subclass <-Super class

Execution result

スクリーンショット 2018-07-02 16.50.08.png

When I try to downcast (assign the parent class Life_form to the child class Cat), the compiler points out that the types are incompatible.

Then how about this (↓)?

Failure example 2


//Subclass <-Super class
public class Main{
  public static void main(String[] args){
    Life_form life_form = new Life_form();
    Cat cat = new Cat();

    cat = (Cat)life_form;       //Subclass <-Super class

If you forcibly cast it like the above program, the compilation will pass. But this time I get a run-time error.

Exception in thread "main" java.lang.ClassCastException: Life_form cannot be cast to Cat at Main.main(Main.java:31)

After all it is pointed out that the type is incompatible.

Then what should I do?

In fact, downcasts are not used directly like upcasts. ** In a downcast, the entity of the superclass instance must be a subclass **. In other words, the parent class cannot be put into the child class as it is.

All you have to do is instantiate the superclass in a subclass and downcast it, as in the code below.

Success story


public class Main{
  public static void main(String[] args){

    Life_form life_form = new Cat();      //Super class <-subclass

    Cat cat = (Cat)life_form;        //Subclass <-Super class

Execution result

スクリーンショット 2018-07-02 17.20.16.png

If you write it like this, you can execute it properly. Note that you need to ** cast it properly (Cat) **.

When do you use downcast?

You can't call catPunch () with the upcast

Downcasts are closely related to upcasts, so let's review a little.

I want to use a class A instance as a function argument, but I also want to specify a class B instance. Upcast was used in such situations.

When Cat is upcast to Life_fome, the entity of Life_form is an instance of Cat class, and Cat class overrides makeSound () function.


 The result of executing is makeSound () of Cat class.

 However, the Cat class-specific function catPunch () cannot be called. ** Even if the entity is Cat, it implicitly behaves as Life_form **.

 When I run catPunch () in the upcast state, it is pointed out like this.
 <img width="327" alt="スクリーンショット 2018-07-02 18.08.36.png " src="https://qiita-image-store.s3.amazonaws.com/0/219573/f3849dd4-54b7-fd94-b1d1-83d70296533c.png ">

 Even though life_form is instantiated in Cat, it is pointed out that "symbol not found" because life_form implicitly behaves as a parent class.

#### So how do you call catPunch ()?
 It's easy. You can downcast it.
 If you look at the code in the "Success example" section and its execution result, you can confirm that catPunch () is available.

 Remember that downcasting is used when you want to use a function that is unique to each instance **.

# Summary
 --Downcast will be used for upcast ones.
 --Use when you want to use an upcast child class instance-specific function.

# Source code
 Details of the classes used in this article.

#### **`Life_form.java`**

//Parent class
public class Life_form{
  public void makeSound(){


//Child class
public class Cat extends Life_form{
  public void makeSound(){

  public void catPunch(){
    System.out.println("Cat bread");



//It is used in the item "Please change the specifications".
public class Dog extends Life_form {
  public void makeSound(){

  public void dogAttack(){

Recommended Posts

I wrote about Java downcast in an easy-to-understand manner
I wrote an overview of Chef in an easy-to-understand manner
I wrote Goldbach's theorem in java
I made an annotation in Java.
I wrote a primality test program in Java
I wrote a prime factorization program in Java
I tried using an extended for statement in Java
What I researched about Java 8
About an instance of java
What I researched about Java 6
I made roulette in Java.
What I researched about Java 9
What I researched about Java 7
About abstract classes in java
I tried metaprogramming in Java
What I researched about Java 5
I made an interpreter (compiler?) With about 80 lines in Ruby.
I created a PDF in Java.
I wrote a Stalin sort that feels like a mess in Java
Try an If expression in Java
I tried using JWT in Java
About file copy processing in Java
What I researched about Java learning
Run an external process in Java
I wrote EX25 of AtCoder Programming Guide for beginners (APG4b) in java.
I wrote a Lambda function in Java and deployed it with SAM
I want to ForEach an array with a Lambda expression in Java
About returning a reference in a Java Getter
[Java] I participated in ABC-188 of Atcorder.
I tried using Elasticsearch API in Java
Map without using an array in java
[Creating] A memorandum about coding in Java
I tried the new era in Java
About Records preview added in Java JDK 14
Continued Talk about writing Java in Emacs @ 2018
I did OpenCV camera calibration in Java
[* Java *] I participated in JJUG CCC 2019 Spring
I made a primality test program in Java
About the confusion seen in startup Java servers
About the idea of anonymous classes in Java
A story about the JDK in the Java 11 era
Try scraping about 30 lines in Java (CSV output)
About var used in Java (Local Variable Type)
Second decoction: Try an If expression in Java
I tried to implement deep learning in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I made a rock-paper-scissors game in Java (CLI)
rsync4j --I want to touch rsync in Java.
What I learned in Java (Part 2) What are variables?
I tried to output multiplication table in Java
How to solve an Expression Problem in Java
I tried to develop an application in 2 languages
I tried to create Alexa skill in Java
[AWS? Docker?] Summarize the necessary knowledge in your portfolio in an easy-to-understand manner [terraform? CircleCI?]
I want to return an object in CSV format with multi-line header & filter in Java