Inheritance & modifier

Posted by elraj on Tue, 14 Sep 2021 03:33:00 +0200

1. Succession

1.1 implementation of inheritance

  • Concept of inheritance

    • Inheritance is one of the three characteristics of object-oriented. It can make subclasses have the properties and methods of the parent class, redefine them in subclasses, and append properties and methods
  • Implement inherited formats

    • Inheritance is implemented through extensions
    • Format: class subclass extends parent class {}
      • Example: class dog extensions animal {}
  • Benefits of inheritance

    • Inheritance can create a relationship between classes and a child parent relationship. After a child parent class is generated, the child class can use the non private members of the parent class.
  • Sample code

    public class Fu {
        public void show() {
            System.out.println("show Method called");
        }
    }
    public class Zi extends Fu {
        public void method() {
            System.out.println("method Method called");
        }
    }
    public class Demo {
        public static void main(String[] args) {
            //Create an object and call a method
            Fu f = new Fu();
            f.show();
    
            Zi z = new Zi();
            z.method();
            z.show();
        }
    }
    

1.2 advantages and disadvantages of inheritance

  • Inherited benefits
    • It improves the reusability of code (the same members of multiple classes can be placed in the same class)
    • The maintainability of the code is improved (if the method code needs to be modified, just modify one place)
  • Inheritance malpractice
    • Inheritance creates a relationship between classes and enhances the coupling of classes. When the parent class changes, the implementation of subclasses has to change, weakening the independence of subclasses
  • Inherited application scenarios:
    • When using inheritance, you need to consider whether there is an is... a relationship between classes. Inheritance cannot be used blindly
      • The relationship between is... A: who is who. For example, teachers and students are a kind of people, that person is the parent, and students and teachers are the children

2. Member access characteristics in inheritance

2.1 access characteristics of variables in inheritance

Accessing a variable in a subclass method adopts the proximity principle.

  1. Subclass local range finding
  2. Subclass member range not found
  3. Parent class member range not found
  4. If there is nothing wrong, report an error (regardless of the father's father...)
  • Sample code

    class Fu {
        int num = 10;
    }
    class Zi {
        int num = 20;
        public void show(){
            int num = 30;
            System.out.println(num);
        }
    }
    public class Demo1 {
        public static void main(String[] args) {
            Zi z = new Zi();
            z.show();	// Output the local variable 30 in the show method
        }
    }
    

2.2 super

  • This & Super keyword:
    • This: represents the reference of this class object
    • super: represents the identification of the storage space of the parent class (which can be understood as the reference of the parent class object)
  • this and super are used respectively
    • Member variables:
      • This. Member variable - access the member variable of this class
      • super. Member variables - access parent member variables
    • Member method:
      • This. Member method - access the member method of this class
      • super. Member method - access parent class member method
  • Construction method:
    • this(...) - access the constructor of this class
    • super(...) - access the parent class constructor

2.3 access characteristics of construction methods in inheritance

Note: all constructors in the subclass will access the parameterless constructors in the parent class by default

Subclasses inherit the data from the parent class and may also use the data from the parent class. Therefore, the parent class data must be initialized before subclass initialization. The reason is that the first statement of each subclass construction method is: super() by default

Question: what if there are no parameterless constructors in the parent class, but only parameterless constructors?

1. through the use of super Keyword to call the parameterized constructor of the parent class
2. Provide a parameterless constructor in the parent class

Recommended scheme:

The method of nonparametric construction is given

2.4 access characteristics of member methods in inheritance

Accessing a method through a subclass object

  1. Subclass member range not found
  2. Parent class member range not found
  3. If there is nothing wrong, report an error (regardless of the father's father...)

2.5 super memory diagram

  • Object in heap memory, there will be a separate super area to store the data of the parent class

2.6 method rewriting

  • 1. Method rewrite concept
    • Subclass as like as two peas in the parent class, the same method declaration (the same as the method name, the parameter list must be the same).
  • 2. Application scenario of method rewriting
    • When a subclass needs the function of the parent class and the subclass of the function subject has its own unique content, you can override the methods in the parent class. In this way, you not only follow the function of the parent class, but also define the unique content of the subclass
  • 3. Override annotation
    • It is used to check whether the current method is a rewritten method and plays the role of verification

2.7 precautions for method rewriting

  • Method override considerations
  1. Private methods cannot be overridden (private member subclasses of the parent class cannot inherit)
  2. Subclass method access permission cannot be lower (public > Default > private)
  • Sample code
public class Fu {
    private void show() {
        System.out.println("Fu in show()Method called");
    }

    void method() {
        System.out.println("Fu in method()Method called");
    }
}

public class Zi extends Fu {

    /* Compile [error], the subclass cannot override the private method of the parent class*/
    @Override
    private void show() {
        System.out.println("Zi in show()Method called");
    }
   
    /* Compile [error]. When the subclass overrides the parent method, the access permission must be greater than or equal to the parent */
    @Override
    private void method() {
        System.out.println("Zi in method()Method called");
    }

    /* Compile [pass]. When the subclass overrides the parent method, the access permission must be greater than or equal to that of the parent */
    @Override
    public void method() {
        System.out.println("Zi in method()Method called");
    }
}

2.8. Considerations for inheritance in Java

  • Considerations for inheritance in Java

    1. Classes in Java only support single inheritance, not multiple inheritance
      • Error example: class A extends B, C {}
    2. Classes in Java support multi-layer inheritance

3. Modifier

3.1 package

  • 1. Package concept
    • A package is a folder used to manage class files
  • 2. Package definition format
    • Package name; (multi-level package. Separate)
    • For example: package com.heima.demo;
  • 3. Compile with package & run with package
    • Compiled with package: javac – d. class name. java
      • For example: javac - D. com.heima.demo.helloworld.java
    • Running with package: java package name + class name
      • For example: java com.heima.demo.HelloWorld

3.2 import

  • Significance of guided packet

    When using classes under different packages, it is too troublesome to write the full path of the class

    In order to simplify the operation with packages, Java provides the function of guiding packages

  • Format of import package

    Format: import package name;

    Example: import java.util.Scanner;

  • Sample code (Scanner object created without import package)

package com.heima;

public class Demo {
    public static void main(String[] args) {
        // 1. Create Scnaner object without import package
        java.util.Scanner sc = new java.util.Scanner(System.in);
    }
}
  • Sample code (Scanner object created after using import package)
package com.heima;

import java.util.Scanner;

public class Demo {
    public static void main(String[] args) {
        // 1. Create Scnaner object without import package
        Scanner sc = new Scanner(System.in);
    }
}

3.3 permission modifier

3.4 final

  • Function of fianl keyword
    • Final stands for the final meaning. It can modify member methods, member variables and classes
  • final modifies the effects of classes, methods, and variables
    • fianl decorated class: this class cannot be inherited (it cannot have subclasses, but it can have parent classes)
    • final modifier method: this method cannot be overridden
    • final modifier variable: indicates that the variable is a constant and cannot be assigned again

3.5 final modifier local variable

  • fianl modifies basic data type variables

    • The final modifier means that the data value of the basic type cannot be changed
  • The final modifier refers to a data type variable

    • The final modification means that the address value of the reference type cannot be changed, but the content in the address can be changed

    • give an example:

      public static void main(String[] args){
          final Student s = new Student(23);
        	s = new Student(24);  // error
       	s.setAge(24);  // correct
      }
      

3.6 static

  • Concept of static
    • Static keyword means static and can modify member method and member variable
  • Characteristics of static modification
    1. Shared by all objects of the class, which is also the condition for us to judge whether to use static keywords
    2. It can be called by class name. Of course, it can also be called by object name [class name is recommended]
  • Example code:
class Student {

    public String name; //full name
    public int age; //Age
    public static String className; //Classrooms are shared data

    public void show() {
        System.out.println(name + "," + age + "," + className);
    }

}

public class StaticDemo {
    public static void main(String[] args) {
	    // Assign a value to the shared data of the object
        Student.className = "9 Teach 313";

        Student s1 = new Student();
        s1.name = "Zhang San";
        s1.age = 30;
        s1.show();

        Student s2 = new Student();
        s2.name = "Li Si";
        s2.age = 33;
        s2.show();
    }
}

3.7 static access features

  • static access features
    • Non static member method
      • Can access static member variables
      • Can access non static member variables
      • Access to static member methods
      • Access to non static member methods
    • Static member method
      • Can access static member variables
      • Access to static member methods
    • In one sentence:
      • Static member methods can only access static members

Topics: Java inheritance