Java inheritance & & modifier

Posted by pfoger on Sat, 12 Feb 2022 06:42:52 +0100

1. Succession

1.1 implementation of inheritance

1. Concept of succession

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 add properties and methods

2. Format of implementing inheritance

  • 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 generating a child parent class, the child class can use the non private members of the parent class
  • Sample code
class Father {
    public void show() {
        System.out.println("show Method called");
    }
}
class Son extends Father {
    public void method() {
        System.out.println("method Method called");
    }
}
public class Demo {
    public static void main(String[] args) {
    
        //Create object and call method
        Father fa = new Father();
        fa.show();
        Son so = new Son();
        so.method();
        so.show();
    }
}

1.2 advantages and disadvantages of inheritance

1. Benefits

  • It improves the reusability of code (the same members of multiple classes can be placed in the same class)
  • It improves the maintainability of the code (if the code of the method needs to be modified, just modify one place)

2. Disadvantages

  • Inheritance creates a relationship between classes, and the coupling of classes is enhanced. When the parent class changes, the implementation of subclasses has to change, weakening the independence of subclasses.

3. Inherited application scenarios:

  • When using inheritance, you need to consider whether there is is is between classes A (who is who) relationship, can not blindly use inheritance.
  • 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 succession

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 the error (regardless of the father's father...)
  • Sample code
class Father {
    int num = 10;
}
class Son {
    int num = 20;
    public void show(){
        int num = 30;
        System.out.println(num);
    }
}
public class Demo {
    public static void main(String[] args) {
        Son son = new Son();
        son.show();// Output local variable 30 in show method
    }
}

2.2 super keyword

1. this and super Keywords:

  • This: represents the reference of this class object
  • super: the identifier representing the storage space of the parent class (which can be understood as the reference of the parent class object)

2. Use of this and super

  • Member variables:
    • this. Member variables - access the member variables of this class
    • super. Member variables - access parent class 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

  • The subclass inherits the data in the parent class and may also use the data of 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 should I do if there is no parameterless constructor in the parent class and only a parameterless constructor?

    1. Call the parameterized constructor of the parent class by using the super keyword
    2. Provide a parameterless construction method in the parent class (recommended)

2.4 method rewriting

1. Method rewrite concept

  • The subclass as like as two peas in the parent class, has the same method declaration as the parent name.

2. Application scenario of method rewriting

  • When the 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, which not only follows the function of the parent class, but also defines the unique content of the subclass.

3. Override annotation

  • It is used to detect whether the current method is a rewritten method and plays the role of verification.

2.5 precautions for method rewriting

1. Precautions for method rewriting

  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 Father {
    private void show() {
        System.out.println("Father in show() Method called");
    }
    void method() {
        System.out.println("Father in show() Method called");
    }
}
public class Son extends Father {

    // Compile [error], the subclass cannot override the private method of the parent class
    @Override
    private void show() {
        System.out.println("Son in show() Method called");
    }
    
    // Compile [error]. When the subclass overrides the parent method, the access permission needs to be greater than or equal to the parent 
    @Override
    private void method() {
        System.out.println("Son in show() 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("Son in show() Method called");
    }
}

2.8 precautions for inheritance in Java (Master)

1. Precautions 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
  • Multi level inheritance example code:
class Grandpa {
    public void drink() {
        System.out.println("Grandpa likes drinking");
    }
}
class Father extends Grandpa {
    public void smoke() {
        System.out.println("Dad loves smoking");
    }
}

class Son extends Father {

}

public class Demo{
    public static void main(String[] args) {
        Son son = new Son();
        
        //Calling the Grandpa class method
        son.drink();
        
        //Call the Father class method
        son.smoke();
    }
}

3. Modifier

3.1 package

1. Concept of package

  • A package is a folder used to manage class files

2. Definition format of package

  • Package name; (multi-level package. Separate)
  • For example: package com fanyi. demo;

3. Compile with package and run with package

  • Compile with package: javac -d Class name java
    • For example: javac - D com. fanyi. demo. HelloWorld. java
  • Running with package: java package name + class name
    • For example: java.com fanyi. demo. HelloWorld

3.2 import keyword

1. Significance of Guide Package

  • 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

2. Format of Guide Package

  • Format: import package name;

  • Example: import Java util. Scanner;

  • Sample code (Scanner object created without import package)

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)
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

Modifier In the same classSubclass independent class in the same packageSubclasses of different packagesUnrelated classes of different packages
private
default
protected
public

3.4 final

1. Function of fianl keyword

  • Final stands for the final meaning. It can modify member methods, member variables and classes

2. Effect of final modifying classes, methods and variables

  • final modified 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
・ final modifier refers to data type variables
. The final modifier 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 (2 4) ; // error
s . setAge (24); / / correct
)

3.6 static (application)

1. The concept of static

  • Static keyword means static. It can modify member methods and member variables

2. 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 and, of course, by object name. (class name calling is recommended)
  • Example code:
class Student {
    public String name; //full name
    public int age; //Age
    public static String school; //Schools share data! So the design is static!
    
    public void show() {
        System.out.println(name + "," + age + "," + school);
    }
}
public class Demo {
    public static void main(String[] args) {

        // Assign a value to the shared data of the object
        Student.school = "university";
        
        Student s1 = new Student();
        s1.name = "Xiao Ming";
        s1.age = 20;
        s1.show();
        Student s2 = new Student();
        s2.name = "Xiao Hong";
        s2.age = 18;
        s2.show();
    }

}

3.7 static access features

  • Non static member method
    • Static members can access variables
    • Access to 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 general, static member methods can only access static members

Topics: Java Back-end