21. Object using object-oriented class -----

1. Description

1.Object class is the root class of the Java class;

2. If not specified parent class extends keyword in the class declaration, the default parent class is java.lang.Object class. Such as:

class Person{}

Equivalent to:

class Person extends Object{}

3. Due to the impact of inheritance, all classes inherit Object class default, if not shown inherit a class, the default inherit the Object class, Object class functions (properties, methods) would have the versatility.

4.Object class only declares an empty argument constructor

2. The main structure

 

 

 3. == operator and equals ()

== operator:

  > Comparison values ​​basic types: as long as the two variables are equal, that is true.

  > Comparative reference type reference (point to the same object): The only point to the same object, == returns true only.

    Person p1 = new Person();

    Person p2 = new Person();

    if(p1 == p2){}

note:

When a "==" is compared, data symbols on both sides must be compatible type (basic type data can be automatically converted excluded), or compiler errors

Code:

public  class Test {
     public  static  void main (String [] args) {
         // for basic data types 
        int A = 10 ;
         int B = 10 ;
         IF (A == B) { 
            System.out.println ( "A = B" ); // A = B 
        } the else { 
            System.out.println ( "A = B!" ); 
        } 

        // for reference data types 
        the Person P1 = new new the Person (); 
        the Person P2 = new new the Person ();
         IF(P1 == p2) { 
            System.out.println ( "P1 and p2 point to the same address" ); 
        } the else { 
            System.out.println ( "references P1 and p2 different address"); // P1 and p2 address different reference 
        } 
    } 
} 

class the person { 
    String name; 
    int Age; 

    public  void eAT () { 
        System.out.println ( "eat" ); 
    } 
}

equals () method:

 

 

 How to override equals ()?

class User{
String name;
int age;
    //重写其equals()方法
    public boolean equals(Object obj){
        if(obj == this){
            return true;
        }
        if(obj instanceof User){
            User u = (User)obj;
            return this.age == u.age && this.name.equals(u.name);
        }
        return false;
    }
}

Note: custom development does not override equals (), automatically generate.

4.toString () method

 

 

 How to override tostring () method?

//自动实现
@Override
public String toString() {
    return "Customer [name=" + name + ", age=" + age + "]";
}

 

 

Author: Java beauty

Date: 2020-03-29

Guess you like

Origin www.cnblogs.com/897463196-a/p/12592679.html