instanceof
check is true.Before Java 17:
Before, you had manually cast an object after asserting it was possible with an instanceof
operation.
if (obj instanceof String) { String s = (String) obj; System.out.println(s.length()); }
After Java 17:
With the new pattern matching, the use of instanceof
immediately automatically casts the object to that type.
if (obj instanceof String s) { System.out.println(s.length()); }
Pet
-class and implementing Cat
-, Dog
– and Hamster
-classes, according to the UML-diagram.main
-method of a PetsApp
-class, make a list of pets.public class PetsApp { public static void main(String[] args) { Pet[] pets = new Pet[]{new Cat("Picasso"), new Dog("Gimli"), new Hamster("Archimedes"),}; for (Pet pet : pets) { pet.makeSound(); pet.feed(); if (pet instanceof Cat c) { c.purr(); } else if (pet instanceof Dog d) { d.wagTail(); } } } }
public abstract class Pet { private String name; public Pet(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public abstract void makeSound(); public abstract void feed(); }
public class Cat extends Pet { public Cat(String name) { super(name); } @Override public void makeSound() { System.out.println("Meow!"); } @Override public void feed() { System.out.printf("Feeding %s with a catnip-based diet...\n", getName()); } public void purr() { System.out.printf("%s is purring...\n", getName()); } }
public class Hamster extends Pet { public Hamster(String name) { super(name); } @Override public void makeSound() { System.out.println("Ssssssssssssssssss!"); } @Override public void feed() { System.out.printf("Feeding %s with a hamster food diet...\n", getName()); } }
instanceof
check is true.