Search code examples
javasuperclass

Java getClass and super classes


public boolean equals(Object o) {
    if (this == o)
        return true;
    if ((o == null) || (this.getClass() != o.getClass()))
        return false;
    else {
        AlunoTE umAluno = (AlunoTE) o;
        return(this.nomeEmpresa.equals(umAluno.getNomeEmpresa()) && super.equals(umAluno);
    }
}

Could anyone explain me how the fourth line ((this.getClass() != o.getClass())) works when the argument is a super class? Because the classes have different names. this.getClass will return a different name than o.getClass, right?


Solution

  • Check the following code snippet which answers your question. Object O can hold any object. o.getClass() will return the run time class of the object

    public class Main {
      void method(Object o) {
        System.out.println(this.getClass() == o.getClass());
      }
    
      public static void main(String[] args) {
        new Main().method(new Object());  // false
        new Main().method(new Main());    // true
        new Main().method(new String());  // false
        new Main().method(new MainOne()); // false
      }
    }
    
    class MainOne extends Main
    {
    }