Java's understanding of the equal method in the Object class

Without further ado, the first example

 1 package Ch_11;
 2 
 3 public class Test {
 4     public static void main(String[] args) {
 5         Object circle1 = new Circle();
 6         Object circle2 = new Circle();
 7         System.out.println(circle1.equals(circle2));
 8     }
 9 }
10 
11 class Circle {
12     double radius;
13     
14     public boolean equals(Object circle) {
15         return this.radius == ((Circle)circle).radius;
16     }
17 }

Answer: true

 1 package Ch_11;
 2 
 3 public class Test {
 4     public static void main(String[] args) {
 5         Object circle1 = new Circle();
 6         Object circle2 = new Circle();
 7         System.out.println(circle1.equals(circle2));
 8     }
 9 }
10 
11 class Circle {
12     double radius;
13 
14     public boolean equals(Circle circle) {
15         return this.radius == circle.radius;
16     }
17 }

Answer: false

 

See here, children, do you have a lot of hello? Of course, do n’t panic, watch my following:

(You must first understand that the parent class cannot directly call the methods of the subclass! Of course, the forced brute force conversion is mentioned separately)

First, you look at this code, Object circle1 = new Circle (); This shows that circle1 is declared as an Object type reference variable, so it is the parent class variable of Circle, so when the seventh line is called, the equal of the Object class is called! ! !

So circle1 and circle2 are of course two different reference type variables, so the return value is of course false!

Also, you have to understand that the equal in the first code is just an overload of the equal method in the parent Object class! ! ! Not rewriting, but the second code is rewriting! ! ! At this point, are you suddenly bright?

 

 

If you still do not understand, welcome to private bloggers, or leave a message in the comment area!

Guess you like

Origin www.cnblogs.com/mr-wei977955490/p/12683350.html