The Java equals () method - as "the semantics of equals in subclasses" defines the use of getClass and instanceof

I am starting to program in Java. I am currently reading about Inheritance and the equals method on the this page . I understand the explanations up to this point:

Compare the classes of this and otherObject. If the semantics of equals can change in subclasses, use the getClass test :

if (getClass() != otherObject.getClass()) return false;

If all subclasses have the same semantics, you can use the instanceof test :

if (!(otherObject instanceof ClassName)) return false;

I don’t understand what the semantics of equals mean. Can someone share the scripts where we use getClass () and instanceof, please?

Thanks for reading.

+4
2

, getClass() . ,

class A { }

class B extends A { }

A B,

A objA = new A();
B objB = new B();

, getClass

System.out.println(objA.getClass()); //Prints "class A"
System.out.println(objB.getClass()); //Prints "class B"

,

objA.getClass() == objB.getClass()

false.

System.out.println(objB instanceof A); //Prints true

, instanceof true, .

, equals(), , (otherObject) ,

 if (getClass() != otherObject.getClass()) return false;

, (otherObject) (ClassName), ,

if (!(otherObject instanceof ClassName)) return false;

" " ", equals()". , .

+3

, equals , getClass , .

getClass

getClass, . , :

MainClass → SubClassLevel1 → SubClassLevel2

MainClass mc = new SubClassLevel2();

, , .

, , x Y . boolean.

, :)

+2

Source: https://habr.com/ru/post/1676885/


All Articles