day10_ Package, static, inheritance, this and super keywords

Posted by cvincent on Mon, 04 Oct 2021 22:47:09 +0200

  Package

The essence of a package is a folder

effect:

  • You can avoid duplicate class names: with a package, the full name of the class becomes: package. Class name
  • Classification organizations manage many classes. If all class files are placed in the same package, it is not conducive to management and later maintenance. Therefore, class files with different functions can be managed in different packages
  • You can control the visibility of certain types or members. If the permission of a type or member is modified by default, it is only used in this package

Declare the syntax format of the package

package name;

Rules and specifications for using packages

  • Must be on the first line of code in the source file
  • A source file can only have one statement declaring a package
  • All words are lowercase. Use. Segmentation between each word
  • Used to invert the company's domain name

How to use classes across packages

Premise: the permission modifier of the used class or member is > default, that is, visible

  • Use the full name of the type, for example: java.util.Scanner input = new java.util.Scanner(System.in);
  • After using the import statement, the simple name is used in the code, and the import statement tells the compiler where to find the class.
  • Using the classes under the java.lang package, you can directly use the simple name without an import statement
  • The import statement must be under package and above class
  • When using classes with the same name in two different packages, for example: java.util.Date and java.sql.Date. One uses a full name and one uses a simple name

static keyword

summary

Static is a static modifier keyword, which means static. It can modify member variables, member methods and code blocks.

static modifier member variable

When static modifies a member variable, the variable is called a class variable. Each object of this class shares the value of the same class variable. Any object can change the value of the class variable, but you can also operate on the class variable without creating the object of the class. Define format:

static data type variable name;  

Access method of static member variables:

Object name. Static member variable name; Not recommended

Class name. Static member variable name;   recommend

Code example

public class Person {
    // Non static variable
    String name;// full name
    // Static variable
    static String country;// nationality

    // Construction method

    public Person() {
    }

    public Person(String name, String country) {
        this.name = name;
        this.country = country;
    }
}

public class Test {
    public static void main(String[] args) {
        // Create Person object
        Person p1 = new Person("Zhang San", "China");
        System.out.println(p1.name+","+p1.country);// Zhang San, China

        System.out.println("=======================");

        // Create Person object
        Person p2 = new Person();
        // country is not decorated with static
        // System.out.println(p2.name+","+p2.country);// null,null
        // Modify country with static
        System.out.println(p2.name+","+p2.country);// null, China

        System.out.println("=======================");

        System.out.println(Person.country);// China
    }
}

static modifier member method

summary

  • The method modified by static will become a static method, also known as a class method, which can be called directly using the class name.

format

Modifier static return value type method name (parameter list){  
        // Method body
}

Access mode

Object name. Method name (argument);
Class name. Method name (argument);   recommend  

Code example

public class Person {
    // Non static method
    public void method1(){
        System.out.println("Person method1...");
    }

    // Static method
    public static void method2(){
        System.out.println("Person method2...");
    }
}
public class Test {
    public static void main(String[] args) {
        /*
            static How to decorate members:
                Format: modifier static return value type method name (formal parameter list) {method body}
                Features: member methods modified by static are called static member methods
                use:
                    Object name. Static member method name (argument);
                    Class name. Static member method name (argument); ------ > recommended
         */
        Person p = new Person();
        p.method2();

        // Class name. Static member method name (argument);
        Person.method2();

    }
}

Precautions for static method invocation:

  • this keyword cannot appear in static methods
  • Only static member variables and static member methods can be accessed directly in static methods
  • Non static member variables and non static member methods cannot be accessed directly in static methods
  • All member variables and member methods can be accessed directly in non static methods

Application of static in future development

  • In future projects, some "global variables" or "global tool methods" are usually required. These global variables and methods can be defined separately in a class and declared as static, which can be easily accessed through the class name

static modifier code block

  •   In java, the code block modified by static is called static code block. Static code block is loaded with the loading of the class and is only executed once. It can be used for member initialization without creating an object. It can be called directly through the class name! When some members in your project must be initialized before the object is created, you can use static code block!
    static {
        System.out.println("Static code block");
    }

inherit

Inheritance is one of the three characteristics of object-oriented. It can make subclasses have the attributes and methods of the parent class, redefine them in subclasses, and add attributes and methods. When there are the same attributes and behaviors in multiple classes, these contents are extracted into a single class, so there is no need to define these attributes and behaviors in multiple classes, but only need to form a certain relationship with the extracted classes As shown in the figure:

Among them, multiple classes can be called subclasses or derived classes; the class extracted from multiple classes is called parent class and superclass Or base class. Inheritance describes the ownership relationship between things. This relationship is the relationship of is-a. for example, in the figure, cats belong to animals and dogs belong to animals. It can be seen that parent classes are more general and subclasses are more specific. Through inheritance, we can form a relationship system between a variety of things.

Benefits of inheritance

  • Improve code reusability.
  • Improve code scalability.
  • The relationship between classes is the premise of learning polymorphism.

Inherited format

With the extends keyword, you can declare that a subclass inherits another parent class. The definition format is as follows:

Code example

/*
 * Define Animal as the parent class
 */
class Animal {
    // Define the name attribute
    String name;
    // Define age attribute
    int age;
    // Define how animals eat
    public void eat() {
        System.out.println(age + "Year old" + name + "I'm eating");
    }
}

/*
 * Define Cat cat inherits Animal Animal
 */
class Cat extends Animal {
    // Define a method of cat catching mouse
    public void catchMouse() {
        System.out.println("Catch a mouse");
    }
}

/*
 * Define test class
 */
public class ExtendDemo01 {
    public static void main(String[] args) {
        // Create a cat object
        Cat cat = new Cat();

        // Assign a value to the name attribute of the cat object
        cat.name = "Tom";

        // Assign a value to the age attribute of the cat object
        cat.age = 2;

        // Call the catchMouse() method of the cat
        cat.catchMouse();

        // Call the eat() method inherited from the cat
        cat.eat();
    }
}

Access rules for post inheritance construction methods

  • The constructor name is consistent with the class name. Constructors cannot be inherited
  • 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, before subclass initialization, you must complete the initialization of the parent class data, because the first statement of each subclass construction method is: super() by default

What if there are no parameterless constructors in the parent class, but only parameterless constructors?

  • Call the parameterized constructor of the parent class by using the super keyword
  • Subclasses call other constructors of this class through this, and other constructors of this class manually call the constructor with parameters of the parent class through super  

Access rules for non private members after inheritance

  • When accessing non private members through "subclasses", find them in the subclass first. If you find them, use the subclass. If you can't find them, continue to find them in the "parent class".

Access rules for private members after inheritance

  • Members in the parent class, whether public or private, will be inherited by the child class.
  • Although the subclass inherits the private members of the parent class, the subclass cannot directly access the inherited private members, which can be accessed through the inherited get/set method. As shown in the figure:

Characteristics of inheritance

  Java only supports single inheritance, not multiple inheritance.

//A class can only have one parent class and cannot have more than one parent class.
class C extends A{} 	//ok
class C extends A,B...	//error

Java supports multi-layer inheritance (inheritance system).

class A{}
class B extends A{}
class C extends B{}

The top-level parent class is the Object class. All classes inherit Object by default as the parent class.

Subclasses and superclasses are relative concepts. For example, class B is a child of class A, but it is a parent of class C

A parent class can have multiple subclasses at the same time

Method rewrite

We say that all method subclasses of the parent class will inherit, but when a method is inherited to a subclass, the subclass feels that the original implementation of the parent class is not suitable for the subclass. What should we do? We can override methods. Subclass appears as like as two peas in the same way as the parent class (the return value type, the method name and the parameter list are the same), and the overlay effect appears, also known as rewriting or copying. The declaration remains unchanged and re implemented.

class Phone {
    public void sendMessage(){
        System.out.println("send message");
    }
    public void call(){
        System.out.println("phone");
    }
    public void showNum(){
        System.out.println("Caller ID number");
    }
}

//Smart phones
class NewPhone extends Phone {

    //Override the caller ID number function of the parent class, and add its own display name and picture function
    public void showNum(){
        //Call the function whose parent class already exists and use super
        super.showNum();
        //Add your own unique function of displaying names and pictures
        System.out.println("Show caller name");
        System.out.println("Show Faces ");
    }
}

public class ExtendsDemo06 {
    public static void main(String[] args) {
        // Create subclass objects
        NewPhone np = new NewPhone();

        // Call the method inherited from the parent class
        np.call();

        // Call the method overridden by the subclass
        np.showNum();

    }
}

Considerations for rewriting

  • Method overrides are relationships that occur between child and parent classes.
  • As like as two peas, the subclass method overrides the parent method. The return value, the method name and the parameter list are exactly the same.
  • When a subclass method overrides a parent method, you must ensure that the access permission is greater than or equal to the parent permission. Access permissions from large to small: public protected (default) private
  • The return value type of the subclass method must be less than or equal to the return value type of the parent method (less than is actually its subclass, for example: Student < person). If the return value type is the basic data type and void, it must be the same
  • Use the @ Override annotation to verify whether the rewriting is successful and verify the rewriting annotation! It is recommended to add this annotation to the rewriting methods. On the one hand, it can improve the readability of the code and prevent rewriting errors on the other hand!
  • Static methods cannot be overridden, private methods that are not visible in subclasses cannot be overridden, and final methods cannot be overridden  

this and super keywords

  • This: a reference to the stored current object. This can access: the member attribute, member method and constructor of this class;
  • super: a reference to the stored "parent object". super can access: member attribute, member method and constructor of parent class;

Three uses of this keyword

This accesses the member variable of this class: this. Member variable

public class Student{
    String name = "Zhang San";
    public void show(){
        String name = "Li Si";
        System.out.println("name = " + name);// Li Si
        System.out.println("name = " + this.name);// Zhang San
    }
}

This accesses the member method of this class: this. Member method name ();

public class Student{
    public void show(){
        System.out.println("show method...");
        this.eat();
    }
    public void eat(){
        System.out.println("eat method...");
    }
}

This access to this class construction method: this() can call another construction method in one construction method of this class.

public class Student{
    public Student(){
        System.out.println("Empty parameter construction method...");
    }

    public Student(String name) {
        this();//When another constructor is called using this(), this code must be the first valid code of this constructor.
        System.out.println("Parametric construction method...");
    }
}
public class Demo {
    public static void main(String[] args) {
        Student stu2 = new Student();
    }
}

Three uses of super keyword

  • Super accesses the member variable of the parent class: super. Name of the member variable of the parent class

class Fu{
    int num = 100;
}

class Zi extends Fu{
    int num = 10;

    public void show(){
        int num = 1;
        System.out.println("local variable num:"+num);// 1
        System.out.println("Zi Class num:"+this.num);// 10
        System.out.println("Fu Class num:"+super.num);// 100

    }
}

Super accesses the member method of the parent class: super. Member method name ();

class Fu{
    public void method1(){
        System.out.println("Fu method1...");
    }
}

class Zi extends Fu{
    public void show(){
        // Access the method1 method of the parent class
        super.method1();
    }

    @Override
    public void method1(){
        super.method1();// Call the method1 method of the parent class
        System.out.println("Zi method1...");
    }
}

Constructor of super access parent class: super()

 class Fu {
    public Fu() {
        System.out.println("Fu Null parameter construction method of class..");
    }

    public Fu(String name, int age) {
        System.out.println("Fu Parametric construction method of class..");
    }
}

 class Zi extends Fu {
    public Zi() {
        super();// Call the null parameter constructor of the parent class
        System.out.println("Zi Null parameter construction method of class..");
    }

    public Zi(String name, int age) {
        super(name, age);// Call the parameterized constructor of the parent class
        System.out.println("Zi Parametric construction method of class..");
    }
}

public class Demo {
    public static void main(String[] args) {
        Zi zi = new Zi();
        System.out.println("----------------------");
        Zi z2 = new Zi("Lau Andy", 17);
    }
}

matters needing attention

  • super access to member variables and member methods: first find it in the parent class. If there is one, use it directly. If not, find it in the grandfather class. If there is one, use it, and so on
  • The constructor of a subclass will call the null parameter constructor of the parent class by default. If there is no null parameter constructor in the parent class and only a parametric constructor is defined, an error will be reported in compilation
  • In the subclass constructor, super is used to call the constructor of the parent class to initialize the properties inherited from the parent class when creating the subclass object
  • Each time a subclass object is created, the parent class space is initialized first, and then the subclass object itself is created. The purpose is that if the subclass object contains its corresponding parent class space, it can contain the members of its parent class. If the parent class member is not private decorated, the subclass can use the parent class member at will. The code is reflected in that when the constructor of a subclass is called, the constructor of the parent class must be called first.
  • this(...) super(...) must be placed in the first valid statement of the constructor, and the two cannot coexist

Topics: Java