[Object and package]

Posted by jokerofsouls on Thu, 10 Feb 2022 15:40:51 +0100

 

catalogue

View source code method

Object class

Definition and Application

1. toString()

2. equals( )

Packaging

Definition and Application

boxing and unboxing

Self implementation of packaging class

Let the Object class receive the basic data type through the wrapper class

Object comparison of wrapper class

Conversion between wrapper class and String

View source code method

Double click the shift key in the IDEA to search for relevant class names and view the source code

Click Structure. The part framed with orange bed on the left is the class Structure, which contains the declarations of all methods, attributes and internal classes. The icon with a small green lock in the Structure indicates public permission, the key icon is protected, and the icon with a red lock is private permission. On the right is the source code.

Object class

Definition and Application

The Object class is the default parent class of all classes and does not need to use extensions to display inheritance. Therefore, all methods of the Object class (except private) can be used by objects of all classes. Therefore, all objects can be received through Object

Example:

        Object obj1 = "test";
        Object obj2 = new Student("Xiao Chen",18);
        Object obj3 = 123;

In Java, the Object class is extended so that it is not only the parent class of all classes, but also can be transformed upward into an Object class as long as it is a reference data type, including arrays and interfaces. In other words, the Object class is the highest parameter unification of the reference data type

Next, let's learn about two common methods in the Object class

1. toString()

Convert any object to string output and print the content of the object. System.out.println() receives any object and outputs it, which is the toString method called by default

Run the following code:

class Student{
    private String name;
    private int age;
    public Student(String name,int age){
        this.name = name;
        this.age = age;
    }
}
public class ObjectTest {
    public static void main(String[] args) {
        Student s1 = new Student("Zhang San",17);
        System.out.println(s1);
    }
}

Operation results:

We can see that it is not the result we expected. Why? Let's take a look at the source code of toString()

To output specific content, you need to override the toString() method:

 public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

//Output: Student{name = 'Zhang San', age=17}

2. equals( )

To compare whether two objects are equal, we usually compare attributes. Following the example above, we create a new object and s1 compare:

        Student s1 = new Student("Zhang San",17);
        Student s2 = new Student("Zhang San",17);
        System.out.println(s1.equals(s2));
//Output: false

s1 and s2 have the same name and age. Why is the output false? Let's take a look at the source code of the equals method

There are new objects when there is new, so s1 and s2 are obviously not the same address. At this time, the Student class uses the equals method provided by the Object class by default. For the Object class, it does not know what properties the subclass has, so it compares the address of the Object.

If we want to compare attribute values, we need to override the equals method:

  public boolean equals(Object obj){
        //Comparison between the current object and the incoming obj
        //1. Judge whether obj is empty
        if (obj == null){
            return false;
        }
        //2. Judge whether obj is itself, that is, the address is the same
        if (obj == this){
            return true;
        }
        //3. Judge whether obj is an object of this class. For example, pass in a string. It is not of Student type and cannot be compared
        if (!(obj instanceof Object) ){
            return false;
        }
        //4. At this time, obj must be an object of Student class, and the two objects do not have the same address
        //Transition down and restore to Student, compare object properties
        Student stu = (Student) obj;
        return this.name.equals(stu.name)&& this.age == stu.age;
    }
}

Override of equals method is very important!!! Be sure to master the instanceof and downward transformation knowledge applied in the code. The links are as follows. You can go and have a look if you are interested

Thoroughly understand Java polymorphism_ m0_ Blog of 58672924 - CSDN blog

Packaging

Definition and Application

The wrapper class encapsulates eight data types into classes:

Object wrapper class

(direct subclass of Object)

Boolean,Character

Numerical packaging

(direct subclass of class Number)

Byte,Short,Integer,Long,Float,Double

Take the # Integer # class as an example:

 public static void main(String[] args) {
        //Set int - > class
        Integer data = new Integer(10);
        //value is to take out the contents of the wrapper class
        int a = data.intValue();
        System.out.println(a);
    }
  //Output: 10

boxing and unboxing

Boxing: changes the basic type to a wrapper class object

Unpacking: restore the value in the packing class object to the basic type

In the above example:

In our actual operation, it is very troublesome to disassemble the box repeatedly. In Java, it provides us with automatic packing and unpacking

Code example:

    public static void main(String[] args) {
        Integer a = 20;
        int b = a+2;
        System.out.println(b);
    }
//Output: 22

You can see that a is an object of Integer class, but it can directly operate with Integer data. In fact, Integer a = 20; Is auto packing, int b = a+2; Is the automatic unpacking process. Therefore, there is no difference between wrapper class and basic type in usage. But remember that the default value of the basic data type is 0 and the default value of the wrapper class is null

So when do we use wrapper classes and basic data types? Alibaba coding protocol stipulates as follows:

  1. To define a member variable in a class, you must use a wrapper class declaration
  2. In methods, a large number of arithmetic operations are performed using basic types

Self implementation of packaging class

public class IntDemo {
    //Save specific integer values
    private int data;
    public IntDemo(int data){
        this.data = data;
    }
    public int intValue(){
        return this.data;
    }

    public static void main(String[] args) {
        //Set int - > class
        IntDemo demo = new IntDemo(10);
        int data = demo.intValue();
        System.out.println(data+1);
    }
}
//Output result: 11

Let the Object class receive the basic data type through the wrapper class

We already know that the Object class can accept all reference types, but it won't work when it comes to basic data types. The wrapper class perfectly solves this problem.  

Use the Object class to receive and modify the main method of the above example as follows:

    public static void main(String[] args) {
        //Set int - > class
        IntDemo demo = new IntDemo(10);
        Object obj = demo;
        IntDemo demo1 = (IntDemo) obj;
        int data = demo1.intValue();
        System.out.println(data+1);
    }
//Output: 11

Object comparison of wrapper class

Unified use of equals method

        Integer a = 10;
        Integer b =10;
        System.out.println(a .equals(b) );
//Output: true

Conversion between wrapper class and String

① Wrapper class -- > string: use string valueOf()

② String -- > wrapper class: use parse * * * () of wrapper class

Code implementation:

      public static void main(String[] args) {
        //Integer -> String
       Integer x = new  Integer(200);
        String y = String.valueOf(x);
        System.out.println(y);

        //String-> Integer
        String str ="123";
        Integer a = Integer.parseInt(str);
        System.out.println(a);
      }
//Output result:
          200
          123

Note that if the String is not composed of pure numbers during String conversion, type conversion exceptions will occur at runtime.  

 

 

Topics: Java Back-end