Loading...
「ツール」は右上に移動しました。
利用したサーバー: wtserver1
64いいね 2,449 views回再生

Learn RUNTIME POLYMORPHISM in 5 minutes! 🤷‍♂️

#java #javatutorial #javacourse

import java.util.Scanner;

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

// Runtime polymorphism = When the method that gets executed is decided
// at runtime based on the actual type of the object.

Scanner scanner = new Scanner(System.in);

Animal animal;

System.out.print("Would you like a dog or a cat? (1 = dog, 2 = cat): ");
int choice = scanner.nextInt();

if(choice == 1){
animal = new Dog();
animal.speak();
}
else if(choice == 2){
animal = new Cat();
animal.speak();
}
}
}

コメント