-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInstanceof.java
More file actions
45 lines (38 loc) · 1.02 KB
/
Instanceof.java
File metadata and controls
45 lines (38 loc) · 1.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class Animal {
void makeSound() {
System.out.println("Animal is making a sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat is meowing");
}
}
public class Instanceof {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
// Using instanceof to check the type of objects
if (animal1 instanceof Dog) {
Dog dog = (Dog) animal1;
dog.bark();
}
if (animal2 instanceof Cat) {
Cat cat = (Cat) animal2;
cat.meow();
}
// Checking for superclass
if (animal1 instanceof Animal) {
System.out.println("animal1 is an instance of Animal");
}
// Checking for non-related types
if (!(animal1 instanceof Cat)) {
System.out.println("animal1 is not an instance of Cat");
}
}
}