Detailed Method of covering - toString () and equals () cover

Before learning this post, it is recommended to complete the learning of my blog - "Detailed inheritance (on) - abstract and layered tools"
Before I Bowen once said that knowledge "base class", then this Bowen topics --Object knowledge base classes and classes on closely related to, and then we go directly to the subject again. **

Object class is a JAVA class type is provided, and is the base class for all classes .

Because all classes are inherited from the Object class , so the method of the Object class in terms of natural has become another class method.

In exceptional cases, when the subclass inherits the parent class for the implementation of the parent class's method may not be satisfied.
To handle this situation, Java also provides a mechanism - covering (or the " method overrides ")

We generally referred to as "covered" because "coverage" is relatively specific image, and "rewrite method" easy and before I explain Bowen as the "method overloading" confusion.

Let's verify the above conclusion:
Here Insert Picture DescriptionFrom the Top: we do not build the Object class, but we can call its methods, and it provides a lot of ways.

Well, I am here to explain about the "coverage" Notes :

Precautions:

  1. The parent class private methods can not be overridden
    because the parent child class private methods simply can not be inherited
  2. When subclasses override the parent class method, access rights can not be lower , the best on a consistent
  3. Parent class static methods , subclass must be rewritten by the static method

We are on this blog mainly on the Object class equals () method and the toString () method covered:

toString () method covered:

First, we use this method to introduce it:

use:

  • If we force this method rewritten (cover), the return value is: package name first name @ address class of the object.
  • Generally, we the members of the class of the target object to override this method so that we can get the value of each member of this object

I used a piece of code and its operating result to show what toString () method:
or our blog post on the class, take a look at the return value of the function:
(here any class can, I order to shorten the readers of amount of reading, so call on Bowen's class)

package com.mec.about_override.demo;

public class Demo {

    public static void main(String[] args) {
        Animal animal =new Animal("动物");
        System.out.println(animal);
    }
    
    
}

Here Insert Picture DescriptionCan be seen from FIG:
Further, when an object or a class is output to a String, the JVM automatically call toString () method.
toString () method of the parameter is " object class ";
the return value is " Package Name first address of the object class name @. ".

Now, to prepare two classes, and the class inherits from another class wherein a
covering of toString () method in the subclass:
Animal.java:

package com.mec.about_override.demo;

public class Animal {
    private String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public void cry() {
        System.out.println("动物的叫声!");
    }
    
}

Dog.java:

package com.mec.about_override.demo;

public class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    
    public void cry() {
        System.out.println("汪汪");
    }
    
    public void dogAction() {
        System.out.println("狗子快跑!");
    }
    
    @Override
    public String toString() {
        return "我是" + getName();
    }
    
}

Demo.java:

package com.mec.about_override.demo;

public class Demo {

    public static void main(String[] args) {
        Dog dog = new Dog("二愣子");
        System.out.println(dog);
    }
    
}

Here Insert Picture DescriptionComparative test results on FIG before and code changes, can be clearly seen, toString () method is covered in accordance with our we use!

equals () methods covered:

首先,本人先来介绍一下这个方法的主要用途:

用途:

  • 若我们不对这个方法覆盖,调用时将比较两个对象的地址值:
    若相同,则返回true;反之,则返回false
  • 一般我们根据这两个对象的类的成员去重写这个方法,以便比较这两个对象的各成员的值是否相同

那么,本人用一段代码 和 它的运行结果 来展示一下equals()方法:
MecPoint.java:

package com.mec.about_equals.core;

public class MecPoint { 

    private int row;    //private表示这个变量只能在该类中被调用。用于防止外类修改该成员
    private int col;

    public final int MIN_ROW = 1;
    public final int MAX_ROW = 25;
    public final int DEFAULT_ROW = 12;
    public final int MIN_COL = 1;
    public final int MAX_COL = 80;      //屏幕点坐标范围:共25行、80列
    public final int DEFAULT_COL = 40;  //默认屏幕点坐标错误时,设为中值   

    public MecPoint() {
        setRow(0);
        setCol(0);
    }

    public MecPoint(int x, int y) {
        setRow(x);
        setCol(y);
    }

    public MecPoint(int x) {    
        setRow(x);
        setCol(0);
    }

    public MecPoint(MecPoint point) {
        setRow(point.row);
        setCol(point.col);
    }
    
    public void setPoint(int x, int y) {
        setRow(x);
        setCol(y);
    }

    public void setPoint(int x) {
        setPoint(x, 0);
    }

    public void setPoint(MecPoint source) {
        setPoint(source.row, source.col);
    }

    public void setRow(int x) {
        if(x <= MIN_ROW || x > MAX_ROW) {   //对x范围进行约束
            x = DEFAULT_ROW;
        }
        row = x;
    } 

    public int getRow() {
        return row;
    }
    
    public void setCol(int y) {
        if(y <= MIN_COL || y > MAX_COL) {   //对y范围进行约束
            y = DEFAULT_COL;
        }
        col = y;
    }

    public int getCol() {
        return col;
    }

    public void printPoint() {
        System.out.println("(" + row + "," + col +")");
    }
    
    @Override
    public String toString() {
        return "(" + row + "," + col + ")";
    }
    
}

Test.java:

package com.mec.about_equals.core;

public class Test {

    public static void main(String[] args) {
        MecPoint pointOne = new MecPoint(3,4);
        MecPoint pointTwo = new MecPoint(3,4);
        
        System.out.println(pointOne);
        System.out.println(pointTwo);
        
        System.out.println(pointOne == pointTwo);
    }

}

现在,我们来看看运行结果:
Here Insert Picture Description
可以看到的是,最后一句的输出是 false
我们明明给两个对象的成员赋的值是一样的,为什么还是false呢?
这样的结果并不奇怪,因为JAVA对于类对象的 == 比较,是对其首地址的比较,而那两个变量占用的是不同的空间,所以无论如何,结果都是false。

现在就是来介绍 equals()方法 的时候啦,现在,我们来给 Test.java 增加一行代码,看看运行结果:
Here Insert Picture Description
哦吼,结果还是false,难道我介绍错了吗?
知道本人一贯作风的同学知道,本人现在在“故弄玄虚”。
没错,这个方法并没有错,但是,这个函数是 Object类 提供的,MecPoint类 只是继承这个方法而已,这个方法并不会自动实现对 row 和 col 成员的比较。

本人先来介绍一个关键字——instanceof:

instanceof keyword;
(1) on the left is an object on the right is a class name;
(2) the object must be a class or sub-class of this class;
(this is not satisfied, the compiler does not pass, can not run)
( 3) if the object is a subclass of the class of the left or right of this class, it returns true,
if the class is a subclass of the class of the right to the left or the object class of the object, false is returned.

Well, we now deal with what the previous question:
We add the following code in MecPoint.java in:

    @Override
    public boolean equals(Object obj) {
        if(null == obj) {
            return false;
        }
        if(this == obj) {
            return true;
        }
        if(!(obj instanceof MecPoint)) {
            return false;
        }
        MecPoint otherPoint = (MecPoint) obj;
        return this.row == otherPoint.row
                && this.col == otherPoint.col;
    }

Here Insert Picture Description
But here I would like to raise the point is: We are writing code in the future, if you want to override equals () method, will first try to cover hashcode (), the reason for this operation, please watch the following blog post:
"cover equals the total to cover hashCode "
(As this knowledge, we can first do not understand, however, to develop good code standards, is very important in future work!)

Finally, it is noted that:
the base class method with a final modification, subclass can not be overwritten.

Guess you like

Origin www.cnblogs.com/codderYouzg/p/12416407.html