Java- copying of objects, difference between abstract classes and interfaces, Object class, object comparison methods and inner classes

Table of contents

1. Clonable interface and deep copy

2. The difference between abstract class and interface

3. Object class

4. Obtain object information

 5. Object comparison method equals

6. Inner class


1. Clonable interface and deep copy

        There are some useful interfaces built into Java, and Clonable is one of them. There is a clone method in the Object class . Calling this method can create a "copy " of an object. But in order to legally call the clone method, you must first implement the Clonable interface , otherwise a CloneNotSupportedException will be thrown.

 

class Students  implements Cloneable {
    public String name;
    public int age;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Students(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "{" +
                "name=" + name +
                ", age=" + age +
                "}";
    }
}
public class text {
    public static void main(String[] args) throws CloneNotSupportedException {
        Students student1=new Students("张三",10);
        Students student2=(Students) student1.clone();//强制类型转化
        System.out.println(student1);
        System.out.println(student2);
    }
}

class Money{
    public double m=25.0;
}
class Students  implements Cloneable {
    public String name;
    public int age;
    public Money money=new Money();

    @Override              浅拷贝
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    public Students(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "{" +
                "name=" + name + " "+
                ", age=" + age +" "+
                ", money=" + money.m +
                '}';
    }
}


public class text {
    public static void main(String[] args) throws CloneNotSupportedException {
        Students student1=new Students("张三",10);
        Students student2=(Students) student1.clone();
        System.out.println(student1);
        System.out.println(student2);
        System.out.println("====");
        student1.money.m=15.0;
        System.out.println(student1);
        System.out.println(student2);
    }
}

 

         Through clone, we just copy the Students object, but the Money object in the Students object is not copied. After modifying the value of m through the reference of student1, when the reference of student2 accesses m, the value also changes .

class Money implements Cloneable{ 
    public double m=25.0; 

    @Override 
    protected Object clone() throws CloneNotSupportedException { 
        return super. clone(); 
    } 
} 
class Students implements Cloneable { 
    public String name; 
    public int age; 
    public Money money=new Mo ney( ); 

    @Override //Deep copy, copy the object in the referenced object (student1) to the target object 
    protected Object clone() throws CloneNotSupportedException { 
        Students temp=(Students) super.clone(); 
        temp.money=( Money)this.money.clone(); 
        return temp; 
    } 

    public Students(String name, int age) { 
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "{" +
                "name=" + name + " "+
                ", age=" + age +" "+
                ", money=" + money.m +
                '}';
    }
}


public class text {
    public static void main(String[] args) throws CloneNotSupportedException {
        Students student1=new Students("张三",10);
        Students student2=(Students) student1.clone();
        System.out.println(student1);
        System.out.println(student2);
        System.out.println("====");
        student1.money.m=15.0;
        System.out.println(student1);
        System.out.println(student2);
    }
}

 

        Through clone, we copy the Students object, and also copy the Money object in the Students object. After modifying the value of m through the reference of student1, when the reference of student2 accesses m, the value will not change .

2. The difference between abstract class and interface

        Both abstract classes and interfaces are common ways of using polymorphism in Java. Both need to be mastered. At the same time, we must recognize the difference between the two, the
        core difference: abstract classes can contain ordinary methods and ordinary fields, such ordinary methods and fields It can be used directly by subclasses (no need to rewrite), and the interface cannot contain ordinary methods, and subclasses must rewrite all abstract methods.
        The significance of the existence of abstract classes is to allow the compiler to check better. We will not use classes like Animal directly, but use its subclasses. In case an instance of Animal is accidentally created, the compiler will promptly Remind us.

3. Object class

        Object is a class provided by Java by default. Except for the Object class in Java, all classes have an inheritance relationship. By default, it will inherit the Object parent class . That is, objects of all classes can be received using Object references.

        For example: use Object to receive objects of all classes. .

class Person{

}
class Student{

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

}

        The Object class has the following methods

4. Obtain object information

        If you want to print the content in the object, you can directly override the toString() method in the Object class.

// The toString() method in the Object class implements
public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode());

 

 5. Object comparison method equals

        In Java, when == is compared: if the left and right sides of == are basic type variables, the comparison is whether the values ​​in the variables are the same;
if the left and right sides of == are reference type variables, the comparison is whether the addresses of the reference variables are the same; If you want to compare the contents of objects, you must rewrite the equals method in Object, because the equals method is also compared by address by default
.

//The equals method in the Object class
public boolean equals(Object obj) {         return (this == obj); // Use the address in the reference to directly compare }

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("zhangsan", 20) ;
                Person p2 = new Person("lisi", 20) ;
                int a = 10;
                int b = 10;

                System.out.println(a == b); 
                System.out.println(p1 == p2); 
                System.out.println(p1.equals(p2));

        }
}

         After the Person class overrides the equals method, then compare:

class Person{
        ...
        @Override
        public boolean equals(Object obj) {
                if (obj == null) {
                return false ;
                }

                if(this == obj) {
                        return true ;
                }

                // Not a Person class object
                if (!(obj instanceof Person)) {                         return false ;                 }

                Person person = (Person) obj ; // Downcast, compare attribute values
                ​​return this.name.equals(person.name) && this.age==person.age ;
        }

}

        Conclusion: When comparing whether the content in the object is the same, the equals method must be rewritten.

6. Inner class

        When there is another part of a thing that needs a complete structure to describe, and the complete internal structure only provides services for external things, then it is best to use the inner class for the complete internal structure. In Java , a class can be defined inside another class or a method, the former is called an inner class, and the latter is called an outer class . Inner classes are also a form of encapsulation.
 // OutClass is the outer class
public class OutClass {
         // InnerClass is the inner class
         class InnerClass {
        }
}
        Note: If defined outside the curly braces of the class name {}, even in one file, it cannot be called an inner class; 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.
public class A {
        ...
}
class B {
        ...
}//A and B are two independent classes
        1. Classification of internal classes
                According to the position of the inner class in a class, it can be divided into instance inner class, static inner class and local inner class.
public class OutClass {
        //Member location: instance inner class (not modified by static)
        public class InnerClass1{
        }
        // Member location: static inner class
        static class InnerClass2{
        }
        public void method(){
                // Define the inner class in the method: Local inner class: hardly used
                class InnerClass5{
                }
        }
}
        2. Inner class
              In the outer class, the definition position of the inner class is the same as that of the members of the outer class, so it is called a member inner class.
              1. Instance inner class 
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();
        // 创建实例内部类对象

        OutClass.InnerClass innerClass1 = new OutClass().new InnerClass();
        // 也可以先将外部类对象先创建出来,然后再创建实例内部类对象(常用)
        OutClass.InnerClass innerClass2 = outClass.new InnerClass();
        innerClass2.methodInner();
        }
}

        Note: Any member of the outer class can be directly accessed in the method of the inner class of the instance; the location of the inner class of the instance is the same as that of the member of the outer class, so it is also subject to the constraints of access qualifiers such as public and private; the object of the inner class of the instance It must be created on the premise that there is an external class object first ; the non-static method of the instance internal class contains a reference to the external class object; in the external class, members in the instance internal class cannot be directly accessed. If you want to access, you must first Create an object of the inner class.

        2. 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(); // 编译报错,methodB()不是静态成员方法
                        methodB();
                }
        }
        public static void main(String[] args) {

                // 静态内部类对象创建 、成员访问
                OutClass.InnerClass innerClass = new OutClass.InnerClass();
                innerClass.methodInner();
         }
}

        Note: Only static members in the outer class can be accessed in the static inner class; when creating a static inner class object, it is not necessary to create the outer class object first.

        3. Anonymous inner class

interface IA { 
    void test(); 
} 
public class text { 
    public static void main(String[] args) { 
        // anonymous inner class 
        IA a = new IA() { 
            @Override 
            public void test() { 
                System.out.println ("This is an overridden interface method!"); 
            } 
        }; 
        a.test(); 
        new IA() { 
            @Override 
            public void test() { 
                System.out.println("This is an overridden interface method method!"); 
            } 
        }.test(); 
    } 
}

        4. Local inner class

        Defined in the method body or {} of the external class, this type of internal class can only be used in the position where it is defined, and is generally used very rarely. Here is a brief understanding of the syntax format.

public class OutClass {
         int a = 10;
        public void method(){
                int b = 10;
                // Local inner class: defined inside the method body
                // cannot be modified by public, static and other access qualifiers
                class InnerClass{
                        public void methodInnerClass(){
                                System.out.println(a);
                                System.out.println(b);
                        }
                }
                // can only be used inside the method body, and cannot be used in other places
                InnerClass innerClass = new InnerClass();
                innerClass.methodInnerClass();
        }
        public static void main(String[] args) {
                // OutClass.InnerClass innerClass = null; compilation error
        }
}

Guess you like

Origin blog.csdn.net/qq_64668629/article/details/132120855