【JAVA】Object class and abstract class

Author's homepage: paper jie_'s blog

Author of this article: Hello everyone, I am paper jie. Thank you for reading this article. Welcome to Yijiansanlian.

This article is included in the column "JAVASE Grammar Series". This column is carefully created for college students and programming novices. The author spent a lot of money (time and energy) to build it to cover all the basic knowledge of javaSE. I hope it can help readers.

Other columns: "JAVA", "Algorithm Detailed Explanation", "C Language", etc.

Content sharing: This issue will explain the Object class and internal classes in JAVA

Table of contents

 

Object class

Get object information toString() method

Object comparison equals method

 hashcode method

inner class

Classification of inner classes

Instance inner class

static inner class

local inner class 

anonymous inner class 


Object class

The Object class is a class provided by default in java. In addition to the Object class in java, all other classes will inherit the Object class by default. So objects of all classes can be received with a reference of the Object class.

Take a chestnut:

class Person{
    
}
class Student{
    
}
public class Test {
    public static void function(Object obj) {
    System.out.println(obj);
}
    public static void main(String[] args) {
        function(new Person());
        function(new Student());
    }
    
}

In the process of Java development, the Object class is the highest unified type of parameters. But the Object class also has some well-defined methods.

These are all methods defined by the Object class:

These methods must be mastered and indispensable for Java learning.

Get object information toString() method

If you want to print the contents of the object, just override the toSting method of the Object class:

// Object类中的toString()方法实现:
    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

The reason is: the object class is the parent class of all classes. After rewriting the tostring method, when using the print method, we will call the rewritten toString method to achieve the effect.

Object comparison equals method

In java, when comparing with ==:

If the two comparison objects are basic types, the comparison is whether the variable values ​​are equal

If the two comparison objects are reference type variables, the comparison is whether the reference addresses are equal

If you want to compare the content in the object, you must rewrite the equals method of the Object class. The equals method defaults to compare by address

// Object类中的equals方法
    public boolean equals(Object obj) {
        return (this == obj); // 使用引用中的地址直接来进行比较
    }
class Person{
    private String name ;
    private int age ;
    public Person(String name, int age) {
        this.age = age ;
        this.name = name ;
    }
}
public class Test {
    public static void main(String[] args) {
        Person p1 = new Person("qeo", 20) ;
        Person p2 = new Person("qeo", 20) ;
        int a = 10;
        int b = 10;
        System.out.println(a == b); // 输出true
        System.out.println(p1 == p2); // 输出false
        System.out.println(p1.equals(p2)); // 输出false
    }
}

The above compares addresses, and if you want to compare their contents, you need to rewrite the equals method:

class Person{
...
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false ;
        } 
        if(this == obj) {
            return true ;
        } // 不是Person类对象
        if (!(obj instanceof Person)) {
            return false ;
        } Person person = (Person) obj ; // 向下转型,比较属性值
        return this.name.equals(person.name) && this.age==person.age ;
    }
}

So when you want to compare whether the contents of the objects are the same, you must rewrite the equals method

 hashcode method

By looking at the source code of the toString method, we found that there is a hashcode method in it:

    public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

Its function is to help us calculate a specific object location. Its result is a memory address and then the toHexString method will be called to print out the address in hexadecimal.

hashcode method source code:

 public native int hashCode();

It is a native method, and the bottom layer is written in c/c++ code, which we cannot see in java.

In our understanding, two objects with the same name and the same age are stored in the same location, but if the hashcode method is not rewritten, the result is different:

class Person {
    public String name;
    public int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}
public class TestDemo4 {
    public static void main(String[] args) {
        Person per1 = new Person("go", 20) ;
        Person per2 = new Person("go", 20) ;
        System.out.println(per1.hashCode());
        System.out.println(per2.hashCode());
    }
} //执行结果
        460141958
        1163157884

At this time we rewrite the hashcode method:

class Person {
    public String name;
    public int age;
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    } @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}
public class TestDemo4 {
    public static void main(String[] args) {
        Person per1 = new Person("go", 20) ;
        Person per2 = new Person("go", 20) ;
        System.out.println(per1.hashCode());
        System.out.println(per2.hashCode());
    }
} //执行结果
        460141958
        460141958

At this time, it was discovered that their hash values ​​were the same.

in conclusion:

The hashcode method is used to determine where the object is stored in memory.

Hashcode is only useful in hash tables. The function of hashcode in hash tables is to obtain the hash code of the object to determine the position of the object in the hash table.

inner class

When a part of the interior of a thing needs a complete structure to describe, and this complete internal structure only needs to provide services for external things, then this internal structure uses internal classes.

In Java, a class can be defined inside another class or method. The former is called an inner class and the latter is called an outer class.

public class OutClass {
    class InnerClass{
    }
} // OutClass是外部类
// InnerClass是内部类

Notice:

If it is defined outside the class name {}, even if it is in a folder, it is not an internal class.

public class A{
}
class B{
} // A 和 B是两个独立的类,彼此之前没有关系

The inner class and the outer class share the same Java source file, but after compilation, the inner class will form a separate bytecode file

Classification of inner classes

According to the different positions of internal classes in the class, they can be divided into the following types:

Member inner classes: instance inner classes that are not statically modified and static inner classes that are statically modified

Local inner classes (not talking about modifiers)

anonymous inner class

public class OutClass {
    // 成员位置定义:未被static修饰 --->实例内部类
    public class InnerClass1{
    } // 成员位置定义:被static修饰 ---> 静态内部类
    static class InnerClass2{
    }
    public void method(){
// 方法中也可以定义内部类 ---> 局部内部类:几乎不用
        class InnerClass5{
        }
    }
}

Instance inner class

Inner classes that are not statically modified:

public class OutClass {
    private int a;
    static int b;
    int c;

    public void methodA() {
        a = 10;
        System.out.println(a);
    }

    public static void methodB() {
        System.out.println(b);
    } //实例内部类:未被static修饰

    class InnerClass {
        int c;

        public void methodInner() {
// 在实例内部类中可以直接访问外部类中:任意访问限定符修饰的成员
            a = 100;
            b = 200;
            methodA();
            methodB();
// 如果外部类和实例内部类中具有相同名称成员时,优先访问的是内部类自己的
            c = 300;
            System.out.println(c);
// 如果要访问外部类同名成员时候,必须:外部类名称.this.同名成员名字
            OutClass.this.c = 400;
            System.out.println(OutClass.this.c);
        }
    }

    public static void main(String[] args) {
// 外部类:对象创建 以及 成员访问
        OutClass outClass = new OutClass();
        System.out.println(outClass.a);
        System.out.println(OutClass.b);
        System.out.println(outClass.c);
        outClass.methodA();
        outClass.methodB();
        System.out.println("=============实例内部类的访问=============");
// 要访问实例内部类中成员,必须要创建实例内部类的对象
// 而普通内部类定义与外部类成员定义位置相同,因此创建实例内部类对象时必须借助外部类
// 创建实例内部类对象
        OutClass.InnerClass innerClass1 = new OutClass().new InnerClass();
// 上述语法比较怪异,也可以先将外部类对象先创建出来,然后再创建实例内部类对象
        OutClass.InnerClass innerClass2 = outClass.new InnerClass();
        innerClass2.methodInner();
    }
}

Notice:

1. Any member in the outer class can be directly accessed in the inner class  

2. The location of the inner class of the instance is the same as the location of the outer class members, so it is also subject to the constraints of access qualifiers such as public and private.

3. When accessing members with the same name in the method of the inner class of the instance, access your own first. If you want to access members with the same name in the outer class, you must access: outer class name.this.members with the same name

4. Instance inner class objects must be created before there is an outer class object.

5. The non-static method of the inner class of the instance contains a reference to the outer class object 

6. In the outer class, you cannot directly access the members of the inner class of the instance. If you want to access, you must first create an object of the inner class.

static inner class

An inner class modified by static is called a static inner class

public class OutClass {
    private int a;
    static int b;
    public void methodA(){
        a = 10;
        System.out.println(a);
    }
    public static void methodB(){
        System.out.println(b);
    } // 静态内部类:被static修饰的成员内部类
    static class InnerClass{
        public void methodInner(){
// 在内部类中只能访问外部类的静态成员
// a = 100; // 编译失败,因为a不是类成员变量
            b =200;
// methodA(); // 编译失败,因为methodA()不是类成员方法
            methodB();
        }
    }
    public static void main(String[] args) {
// 静态内部类对象创建 & 成员访问
        OutClass.InnerClass innerClass = new OutClass.InnerClass();
        innerClass.methodInner();
    }
}

Notice:

Only static members in the outer class can be accessed in a static inner class 

When creating a static inner class object, there is no need to create an outer class object first 

local inner class 

Defined in the method body or {} of the outer class, this kind of inner class can only be used in the position where it is defined, and is generally used very rarely:

public class OutClass {
    int a = 10;
    public void method(){
        int b = 10;
// 局部内部类:定义在方法体内部
// 不能被public、static等访问限定符修饰
        class InnerClass{
            public void methodInnerClass(){
                System.out.println(a);
                System.out.println(b);
            }
        } // 只能在该方法体内部使用,其他位置都不能用
        InnerClass innerClass = new InnerClass();
        innerClass.methodInnerClass();
    }
    public static void main(String[] args) {
// OutClass.InnerClass innerClass = null; 编译失败
    }
}

Notice:

1. Local inner classes can only be used inside the defined method body

2. Cannot be modified by public, static and other modifiers

3. The compiler also has its own independent bytecode file. The naming format is: external class name $ number internal class name.class

4. Hardly used 

anonymous inner class 

This inner class has no name:

interface IA {
    void test();
}


public class Test {
    public static void main(String[] args) {
        IA a = new IA() {
            @Override
            public void test() {
                System.out.println("重写的方法");
            }
        };
        a.test();
    }


 

Guess you like

Origin blog.csdn.net/paperjie/article/details/132684042