Upcasting is a feature that allows a subclass (child class) to implicitly act as a superclass (parent class).
In development, specification changes are inherent. At the time of such a specification change, if the program is written using upcast, the rewriting of the program due to the change can be minimized.
Let me give you an example from the program.
Main.java
public class Main{
public static void main(String[] args){
Life_form life_form = new Life_form();
life_form.makeSound();
//Upcast
life_form = new Cat();
life_form.makeSound();
}
}
Life_form.java
//Parent class
public class Life_form{
public void makeSound(){
System.out.println("???");
}
}
Cat.java
//Child class
public class Cat extends Life_form{
@Override
public void makeSound(){
System.out.println("nyaa");
}
public void catPunch(){
System.out.println("Cat bread");
}
}
Dog.java
//It is used in the item "Please change the specifications".
public class Dog extends Life_form {
@Override
public void makeSound(){
System.out.println("Kuhn!");
}
public void dogAttack(){
System.out.println("Biting");
}
}
-The Life_form class has a makeSound function. -The Cat class inherits the Lifeform class and redefines (overrides) the makeSound function. -In addition, the Cat class has a limited function, the catPunch function, which the parent class does not have.
The Dog class is used in the following items, "Please change the specifications". It is made in the same way as the Cat class, overrides makeSound, and has a dog attack limited to the Dog class.
What I want you to pay attention to in the Main class
life_form = new cat();
I'm trying.
Assigning a child class to a parent class. This is an upcast.
The execution result is as follows.
It's a little hard to see, but you can see that the Cat instance makeSound () is called from life_form by upcasting.
In other words, the entity of life_form after `life_form = new Cat ();`
is an instance of Cat.
Now, if you are asked to change the Cat instance of this program to a Dog instance, you only need to make the following changes.
life_form = new cat();
->life_form = new Dog();
If the upcast didn't exist as a feature, the changes would be:
1st
life_form = new cat();
->Dog dog = new Dog();
2nd
life_form.makeSound();
->```dog.makeSound();```
First of all, it is necessary to create an instance with Dog type, and even where it is used, dog must be used.
You might think it wouldn't change that much.
But that's because it's a very small program.
The larger the development, the more changes and the more changes.
It is important to create a program that is resistant to specification changes. And java has the ability to do that.
I want to use it well.
Recommended Posts