RehAm EL-Gamal RehAm EL-Gamal - 5 months ago 4x
Java Question

what does it mean by having 2 equal classes?

public boolean isAfraidOf(Animal animal) {
//Compare the class of this animal to Bird
if (animal.getClass() == Bird.class) {
return false;
} else {
return true;

Animal is the super class and Bird is the subclass , i need to know the differentiator on which they compare the two classes? and thanks in advance


getClass() returns the Class. So animal.getClass() would return type Animal and the comparison would return false.

So here is a comprehensive study for your understanding:

Animal animal = new Animal();

Bird bird = new Bird();

Animal birdAnimal = new Bird();

if (animal.getClass() == bird.getClass()){
    System.out.println("Bird equals to animal");
    System.out.println("Bird not equals to animal");

if (birdAnimal.getClass() == animal.getClass()){
    System.out.println("BirdAnimal equals to animal");
}else {
    System.out.println("BirdAnimal not equals to animal");

if (animal.getClass() == Animal.class){
    System.out.println("animal equals to Animal");
    System.out.println("animal not equals to Animal");

if (animal.getClass() == Bird.class){
    System.out.println("animal equals to Bird");
    System.out.println("animal not equals to Bird");

And here is the output:

Bird not equals to animal
BirdAnimal not equals to animal
animal equals to Animal
animal not equals to Bird