Object oriented (code block, inheritance, difference between method rewriting and method overloading, final keyword)

Keywords: Java Back-end

1. Overview and classification of code blocks

1. Code block overview
     In Java, code enclosed with {} is called a code block.
2. Code block classification
     According to its location and declaration, it can be divided into local code block, construction code block, static code block and synchronous code block (multi-threaded explanation).
3. Application of common code blocks
     a: Local code block  
         Appear in the method; Limit variable life cycle, release as soon as possible, and improve memory utilization
     b: Construct code block  
         Occurs outside the method in the class; The same code in multiple construction methods is stored together, and the construction is executed every time it is called, and it is executed before the construction method
     c: Static code block  
         It appears outside the method in the class and is decorated with static
         It appears outside the method in the class and is decorated with static; It is used to initialize the class. It is executed when loading, and only once.

Local code block:

public class MyTest {
    public static void main(String[] args) {
        //Code block: code that is expanded by a pair of braces.
        //Code blocks are divided into local code blocks, construction code blocks and static code blocks according to the defined positions. Synchronous code block (later)
        //Local code block, the code block defined in the method.
        //Construction code block: defined outside the method in the class and at the same level as the construction method
        //Static code block: a code block modified with static, which is defined outside the methods in the class
        int a=100;

        {
            //Appear in the method; Limit variable life cycle, release as soon as possible, and improve memory utilization
            int num=100;
            System.out.println("This is a partial code block"+num);
            System.out.println(a);
        }

      // System.out.println(num);

    }
}

  Student class:

public class Student {
   static int num=100;
    {
        System.out.println("This is the construction code block");
    }
    static{
        System.out.println("This is a static block of code");
        System.out.println("Static code blocks are commonly used. They often do some initialization preparations in static code blocks.");
        System.out.println(num);
    }
    public Student() {
        System.out.println("This is an empty parameter structure");
    }
}

Test class:

public class MyTest2 {
    public static void main(String[] args) {
        //When an object is created, the construction code block is called and takes precedence over the execution of the construction method. Each time an object is created, the construction code block is called.
        //Static code blocks, which are loaded with the loading of classes, take precedence over the execution of constructed code blocks. And will be executed only once. In static code blocks, only static members can be accessed.
        Student student = new Student();

        Student student1 = new Student();
    }
}


2. Code block interview questions

Look at the program and write the results
    class Student {
        static 
             System.out.println("Student static code block");  // three
        }
        
        {
             System.out.println("Student construction code block")// 4 6
        }
        
        public Student() {
             System.out.println("Student construction method")// 5 7
        }
    }

    class StudentDemo {
        static {
             System.out.println ("static code block of studentdemo")// one
        }
        
        public static void main(String[] args) {
             System.out.println("I am the main method")// two
        
            Student s1 = new Student();
            Student s2 = new Student();
        }
    }  


3. Introduction and overview of succession

1. Overview of succession
     When the same attributes and behaviors exist in multiple classes, these contents are extracted into a single class, so multiple classes do not need to define these attributes and behaviors, just inherit that class.
2. Inheritance format
     Class to class inheritance can be realized through the extends keyword
     Class subclass name extends parent class name {}  
     A separate class is called a parent class, base class, or superclass; These classes can be called subclasses or derived classes.


4. Demonstration of inheritance cases and advantages and disadvantages of inheritance

1. Demand:
    Dog class, Cat class and Animal class.
     Define two functions (eat, sleep)
2. Case demonstration
     Before using inheritance
3. Case demonstration
     After using inheritance
4. Benefits of inheritance
     a: It improves the reusability of the code
     b: Improved code maintainability
     c: Making the relationship between classes is the premise of polymorphism
5. Disadvantages of inheritance
     Class coupling is enhanced.
     Development principle: high cohesion, low coupling.
     Coupling: class to class relationships
     Cohesion: the ability to accomplish something

Animal class:

public class Animal {
    String name;
    int age;

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

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

Dog class:

public class Dog extends Animal{


    public void lookDoor(){
        System.out.println("Janitor");
    }

}

Cat class:

public class Cat extends Animal{

    public void catchMouse(){
        System.out.println("Catch a mouse");
    }
}

Test class:

public class MyTest {
    public static void main(String[] args) {
        //Three characteristics of object-oriented: class inheritance polymorphism
        //Inheritance in life: a son can inherit Lao Tzu's property.
        //Inheritance in Java: subclasses can inherit members of the parent class.
        //You can use the extends keyword to form a parent-child relationship between classes.
        //Advantages of inheritance: it can improve the reusability and maintainability of code.
        //The idea of inheritance: the common content of multiple subclasses is extracted upward into the parent class to realize the reusability and maintainability of the code.
        //Disadvantages of inheritance: it creates a relationship between classes and increases coupling.
        //Software design principles: high cohesion (something completes its function independently) and low coupling
        Cat cat = new Cat();
        cat.name="Tom";
        cat.age=15;
        System.out.println(cat.name);
        System.out.println(cat.age);
        cat.eat();
        cat.sleep();
        cat.catchMouse();

        System.out.println("====================================");
        Dog dog = new Dog();
        dog.name="Wangcai";
        dog.age=5;
        System.out.println(dog.name);
        System.out.println(dog.age);
        dog.sleep();
        dog.eat();
        dog.lookDoor();
    }
}


5. Inheritance characteristics of classes in Java

1. Inheritance characteristics of classes in Java
     a:Java only supports single inheritance, not multiple inheritance.
         Some languages support multiple inheritance, format: extensions, class 1, class 2
     b:Java supports multi-layer inheritance (inheritance system)
2. Case demonstration
     Inheritance characteristics of classes in Java


6. Considerations for inheritance and when to use inheritance

1. Considerations for succession
     a: A subclass can only inherit all non private members (member methods and member variables) of the parent class
     b: Subclasses cannot inherit the constructor of the parent class, but the constructor of the parent class can be accessed through the super keyword.
     c: Don't inherit for some functions
2. When to use inheritance
     Inheritance actually embodies a relationship: "is a"         
     The hypothesis method is adopted.
         If there are two classes A,B. Only if they meet that A is A kind of B, or B is A kind of A, inheritance can be considered.

public class MyTest {
    public static void main(String[] args) {
        //Precautions for inheritance;
        //1. In Java, only single inheritance is supported. A subclass can only have one parent class and cannot have multiple parents, but multi-layer inheritance is supported.
        //Object is the top-level parent class of all classes, and all classes inherit from it directly or indirectly.
        //2. The construction method does not participate in inheritance. When we create a subclass object, we will first call the constructor of the parent class to complete the initialization of the parent class data.
        //3. The parent class is a private member, and the child class cannot inherit.

        Zi zi = new Zi();
        System.out.println(zi.a);
        System.out.println(zi.b);
        //zi.fu();
    }
}

class A extends Object{
    int a=100;
    private int bb=20;
}

class Fu extends A{
    int b=20;
    private double cc=3.14;

    private void fu(){

    }
}

class Zi extends Fu{

}

 


7. Relationship between member variables in inheritance

1. The name of the member variable in the subclass is different from that in the parent class
2. The name of the member variable in the child class is the same as that in the parent class
     The search order for accessing a variable in a subclass ("proximity principle")
         a: Find the local scope of the subclass method and use it if necessary
         b: Find the member range of the subclass and use it if necessary
         c: If it is found in the member range of the parent class, it will be used
         d: If you can't find it, report an error


8. Difference and application between this and super

1. Lead to super through questions
     Subclass local scope accesses parent class member variables
2. Tell me the difference between this and super
     this     Represents the reference of this class object
     super   It represents the identification of the storage space of the parent class (it can be understood as a reference of the parent class and can operate on the members of the parent class)
3. Use of this and super
     a: Call member variable
         This. Member variable   Call the member variable of this class
         super. Member variable      Call the member variable of the parent class
     b: Call constructor
         this(...)              Call the constructor of this class
         super(...)              Call the constructor of the parent class
     c: Call member method
         This. Member method          Call the member method of this class
         super. Member method      Call the member method of the parent class

practice:

public class MyTest {
    public static void main(String[] args) {
        Zi zi = new Zi();
        zi.show(5);
    }
}

class Fu{
    int num=100;
}

class Zi extends Fu{
    int num=20;

    public void show(int num){
        System.out.println(num); //5
        System.out.println(this.num); //20
        System.out.println(super.num); //100
    }
}

Father class:

public class Father {
    int num = 3000;
    double aa =6.999;
    boolean flag=true;

    public void show() {
        System.out.println("Parent class show method");
    }

    public void hehe() {
        System.out.println("Parent class hehe method");
    }
}

Son class:

public class Son extends Father {
    int num=100;
    double aa=3.14;

    char ch='a';

    public void ziShow(int num){
        /*
        * Access principle of variables: follow the principle of proximity. First find the local range (within the method and formal parameters). If you can't find it, go to the member range of this class (member variables)
        * If the member range of this class is not found, go to the parent class member range to find it and use it. If it is not found again, an error will be reported.
        *
        * When the local variable, this class member variable and parent class member variable have the same name, you can use this super to distinguish them.
        *
        *
        * */
        System.out.println("Subclass show method");
        System.out.println(num);
        System.out.println(this.num);
        System.out.println(super.num);
        System.out.println(aa);
        System.out.println(super.aa);
        System.out.println(this.aa);
        System.out.println(flag);
        System.out.println(super.flag);
        System.out.println(this.flag);

        System.out.println(ch);
    }


    public void haha(){
        this.show(); //The show() method of the parent class is inherited by you, which is equivalent to yours, so you can add this before it.
        super.show(); //Call the method of the parent class
        this.hh(); //Call this class method
    }

    public void hh(){
        System.out.println("hhhhhhhh");
    }
}

Test class:

public class MyTest {
    public static void main(String[] args) {
        //this and super
        //super: represents an identifier of the parent class space. You can think of it as a reference of the parent class. You can use it to access the data of the parent class.
        //This: represents a reference of this class. If you use this, you will access the data of this class.
        //Accessing member variables
        //This. Member variable this.num
        //Super. Member variable super.num
        //Access member method:
        // This. Member method name (this. Show)
        // Super. Member method name () super.show()
        // Access construction method
        // this()
        // super()

        Son son = new Son();
        son.ziShow(20);
        son.haha();
    }
}


9. Relationship between construction methods in inheritance

1. Case demonstration
     By default, all constructors in the subclass will access the constructors of the null parameters of the parent class
2. Why?
     Because the child class inherits the data in the parent class, it may also use the data of the parent class.
     Therefore, before subclass initialization, you must complete the initialization of parent class data.
    
     Actually:
         The first statement of each constructor is: super() by default
        The Object class is the parent class.

public class MyTest {
    public static void main(String[] args) {
        //Father father = new Father();
        //When I create a subclass object, why do I call the null parameter construction method of the parent class first? Why?
        /*
        *  Because the subclass inherits the parent class, that is, the subclass inherits the data of the parent class and even uses the data of the parent class,
        * Therefore, when we create a subclass object, we should complete the initialization of the parent class data first, so that the subclass can inherit the parent class data and use the parent class data.
        * Since you need to initialize the parent class data first, you must call the constructor of the parent class first to complete the initialization of the parent class data.
        *
        * */
        Son son = new Son();
    }
}

class Father{
    int num=100;
    public Father() {
        System.out.println("Father The null parameter construction of the parent class is executed");
    }
}

class Son extends Father{
    int s=20;
    public Son() {
        super();
        System.out.println("son The null parameter construct of is executed"+num+"==="+s);
    }
}

 


10. Considerations for construction methods in inheritance

1. Case demonstration
     The parent class has no parameterless construction method. What about the child class?
     a: Add a parameterless constructor to the parent class
     b: The subclass uses super to display and call other construction methods with parameters of the parent class
     c: Subclasses use this to call other constructor methods of this class
         Other constructs of this class must first access the parent class construct
2. Precautions
     super(...) or this(...) must appear on the first statement

public class MyTest {
    public static void main(String[] args) {
        //When I create a subclass object, why do I call the null parameter construction method of the parent class first? Why?
        /*
         *  Because the subclass inherits the parent class, that is, the subclass inherits the data of the parent class and even uses the data of the parent class,
         * Therefore, when we create a subclass object, we should complete the initialization of the parent class data first, so that the subclass can inherit the parent class data and use the parent class data.
         * Since you need to initialize the parent class data first, you must call the constructor of the parent class first to complete the initialization of the parent class data.
         * How to call the constructor of the parent class? In fact, in the first line before the constructor of each class, there is a default statement super(), which calls the null parameter constructor of the parent class
         *
         * */

        Zi zi = new Zi();
        /*
        *
        *  What if the parent class does not provide null parameter construction?
        * //1. You manually provide an empty parameter construct.
        * //2. You can call the parent class parameter constructor.
        * */
    }
}

class Fu extends Object{
    int num=200;
    /*
    public Fu() {
        super();
        System.out.println("The constructor of the parent class called ');
    }

     */
    public Fu(int num){
        System.out.println("The constructor of the parent class called");
        System.out.println(num);
    }
}
class Zi extends Fu{
    int aa=20;
    public Zi() {
        //super();
        //super(10); / / call the parameterized construction of the parent class
        this(20); //Call the parameterized construction of this class
        System.out.println("The constructor of the subclass called");
    }

    public Zi(int num){
        super(num);
        System.out.println("The parameterized constructor of a subclass called");
    }
}

11. Interview questions in succession

1. Case demonstration
     Look at the program and write the result 1
    class Fu{
        public int num = 10;
        public Fu(){
            System.out.println("fu"); //1
        }
    }
    class Zi extends Fu{
        public int num = 20;
        public Zi(){
            System.out.println("zi"); //2
        }
        public void show(){
            int num = 30;
            System.out.println(num); //30
            System.out.println(this.num); //20
            System.out.println(super.num); //10
        }
    }
    class Test {
        public static void main(String[] args) {
            Zi z = new Zi();
            z.show();
        }
    }

2. Case demonstration
     See the program write results 2
    class Fu {
        static {
             System.out.println("static code block Fu")//   one
        }

        {
             System.out.println("construction code block Fu"); //3
        }

        public Fu() {
             System.out.println("construction method Fu");   // four
        }
    }

    class Zi extends Fu {
        static {
             System.out.println("static code block Zi");//2
        }

        {
             System.out.println("construction code block Zi"); //5
        }

        public Zi() {
            super();
             System.out.println("construction method Zi"); //6
        }
    }
    
    class Test{
        public static void main(String[] args){
             Zi z = new Zi(); / / what is the execution result.
        }
    }


12. Member method relationship in inheritance

A: Case demonstration
     a: When the method name of the child class is different from that of the parent class
     b: When the method name of the child class is the same as that of the parent class
         Calling methods through subclasses:
             a: First find out whether there is this method in the subclass. If so, use it
             b: If there is such a method in the parent class, use it
             c: If not, report an error


13. Overview of method rewriting and its application

1. What is method rewriting
     Subclass as like as two peas in the parent class, the method declaration (method name, parameter list, return value type) is also known as method coverage and method duplication.
2. The difference between override and Overload? Can Overload change the return value type?
3. Application of method Rewriting:
     When the subclass needs the function of the parent class, and the subclass of the function body has its own unique content, you can override the methods in the parent class.
     In this way, not only the functions of the parent class are followed, but also the specific contents of the child class are defined.
4. Case demonstration
     a: Define a mobile phone class.
     b: Through research, I invented a new mobile phone. The function of this mobile phone is to call both voice and video.

Phone class:

public class Phone {

    public void call(){
        System.out.println("voice call ");
    }
}

IPhone class:

public class IPhone extends Phone {
    //Method rewrite: as like as two peas appear in the same way as the parent class (return value type, method name, parameter), subclass method will overlay the method of overlaying the parent class.
    //Why is there such a mechanism for method rewriting? Because it is possible that the subclass is dissatisfied with the method implementation of the parent class and wants to implement it according to its own logic, it can override the method of the parent class through method rewriting.
    //ctrl+O can quickly override parent methods
    @Override//Note: you can check whether the method overrides the parent class
    public void call() {
        super.call(); //Continue to use the functions of the parent class
        System.out.println("Video call");
    }
}
Test class:
public class MyTest {
    public static void main(String[] args) {
        IPhone iPhone = new IPhone();
        iPhone.call();
    }
}

14. Precautions for method rewriting

1. Precautions for method rewriting
     a: Private methods in a parent class cannot be overridden
         Because the private method subclass of the parent class cannot inherit at all
     b: When the subclass overrides the parent method, the access permission cannot be lower, and it is better to be consistent
     c: The parent class is a static method and does not participate in rewriting
     As like as two peas, the best way to declare a parent is to declare exactly the same.
2. Case demonstration
     Method override considerations

public class MyTest {
    public static void main(String[] args) {
        //Precautions for method Rewriting:
        //1. When the subclass overrides the method of the parent class, the permission modifier of the method cannot be lower than that of the parent class, but higher or the same as that of the parent class.
        //2. Subclasses of private methods of the parent class cannot be overridden, because private method subclasses cannot inherit. How can we talk about rewriting.
        //3. The construction method cannot be rewritten,
        //4. Static methods are not rewritten

        Zi zi = new Zi();
        zi.hehe();
        Zi.hehe();
        Fu.hehe();
    }
}

class Fu {
    void show() {
    }
    public static  void hehe(){
        System.out.println("Parent class static method");
    }
}

class Zi extends Fu {
    @Override
    public void show() {
    }

    //@Override
    public static void hehe() {
        System.out.println("Subclass static method");
    }
}

 

15. Use the cases of students and teachers before inheritance

      Use inherited student and teacher cases

human beings:

public class Person {
    String name;
    int age;

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

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

  Students:

public class Student extends Person{
    @Override
    public void eat() {
        System.out.println("Students like spicy hot");
    }

    @Override
    public void sleep() {
        System.out.println("Students like sleeping in class");
    }

    public void homeWrok(){
        System.out.println("do the homework");
    }
}

Teachers:

public class Teacher extends Person{

    @Override
    public void eat() {
        System.out.println("The teacher likes burning noodles");
    }

    @Override
    public void sleep() {
        System.out.println("The teacher goes to bed at night");
    }

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

Test class:

public class MyTest {
    public static void main(String[] args) {
        Student student = new Student();
        student.name="Zhang San";
        student.age=20;
        System.out.println(student.name);
        System.out.println(student.age);
        student.sleep();
        student.eat();
        student.homeWrok();
        System.out.println("===============================================");
        Teacher teacher = new Teacher();
        teacher.name = "Lao Li";
        teacher.age=30;
        System.out.println(teacher.name);
        System.out.println(teacher.age);
        teacher.eat();
        teacher.sleep();
        teacher.teach();


    }
}

 

16.final keyword overview

1. Why is there final
     Because there is a method override in inheritance, and sometimes we don't want the subclass to override the method of the parent class. In this case, java provides us with a keyword: final
2.final overview
     Final keyword is the final meaning. It can modify classes, variables, members and methods.

17.final keyword modifies the characteristics of classes, methods and variables

1.final modification features
     Decoration class:          The decorated class cannot be inherited
     Modification method:      Modified methods cannot be overridden
     Modifier variable:      The modified variable cannot be reassigned because the quantity is actually a constant
2. Case demonstration
     final modification features

18.final keyword modifies a local variable

The basic type is a value that cannot be changed
The reference type is the address value and cannot be changed

public class MyTest {
    public static final int A=100;  //public final static 
    public static void main(String[] args) {
      //  Finally, you can modify variables, methods and classes
        //1. final modifies a variable. This variable is a constant. The constant name is capitalized.
       final int NUM=20;
        System.out.println(MyTest.A);

        //2.final modification method this method cannot be overridden. Subclasses can inherit the final method and cannot be overridden.
        Zi zi = new Zi();
        zi.show();

        //3. final modifier class, which cannot be inherited


        final int a=20;
        //final modifies a variable of basic data type, which means that the value cannot be changed.

      final Zi zi1 = new Zi();
        //zi1=new Zi();
        //The final modifier refers to a variable that references a data type. It means that the address value cannot be changed.


    }
}

class Fu{
    public final void show(){}
}
class Zi extends Fu{
    //public final void show()
}

Posted by deniscyriac on Tue, 02 Nov 2021 08:17:10 -0700