java week 3 Summary

Posted by HaZaRd420 on Sat, 15 Jan 2022 03:58:35 +0100

1: Introduction and precautions of static keyword

1.1 static features:

  1. Loads as the class loads
  2. Priority object exists. Because when there is no new object, the static modified variable or method has been loaded and stored in the static method area.
  3. static keyword cannot coexist with this. Because: This represents the object of the current class.
class staticDemo1{
    static int age;
    public static void test(){
       int a= staticDemo1.age;
        System.out.println(a);
    }
}

public class staticDemo {

    public static void main(String[] args) {
// static modified variables and methods are not recommended to create objects to call
//      staticDemo1 s = new staticDemo1();
//      s.test();
// Class names are recommended Variable or method
        staticDemo1.test();
    }
}
  1. As shown above: if the static variable does not show data at compile time, the default value is "0" at compile time
  2. Statically modified objects can be shared by multiple objects: it means sharing

1.2 note:

  1. Class name is recommended for static modified variables and methods Static variables / methods, direct use
  2. The static keyword cannot be used with this. This represents the object of the current class
    The address value of (similar to the created object. But static takes precedence over new (create object), so it can't be used together).

2: Sequence of code blocks

2.1 definition of code block

There is no code in the program that the connection method is included by {}.

2.2 code block classification mainly includes the following categories.

  1. Local code block
  2. Construct code block
  3. Static code block

2.3 code block execution priority

Static code block > construction code block > local code block

3: Inherit

Inheritance is one of the three major features of java. Inheritance is to extract the same attributes (Methods) of multiple classes into an independent class, and then the independent class has a close relationship with these classes - inheritance

3.1 inherited advantages:

  1. Easy maintenance
  2. Improve code reusability;
  3. Inheritance is a prerequisite for polymorphism

example:

class people{
    private String name;
    private int age;
    private String gender;
    public people(){}
    public people(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    //Nonparametric structure
    public String getName() {
        return name;
    }
    //Parametric structure
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    //Unique method
    public void eat(){
        System.out.println(name+age+gender+":I like chocolate");
    }
}

public class extendsDemo extends people{
    public extendsDemo() {
    }

    public extendsDemo(String name, int age, String gender) {
        super(name, age, gender);
    }

    public static void main(String[] args) {
        people p = new people("Zhang San", 28, "male");
        p.eat();
    }
}

3.3 characteristics of inheritance

  1. In the java language, inheritance only supports single inheritance, not multiple inheritance, but multi-layer inheritance

3.4 format of inheritance writing

  1. The writing format is: class name extends parent class {}

3.5 keywords in inheritance

  1. estends: the subclass inherits the keyword of the parent class
  2. super: refers to the address of the parent object in the subclass, which is equivalent to a new parent class

3.6 precautions in inheritance

  1. A subclass inherits from the parent class and can only inherit public properties and public methods. Private properties and methods cannot be accessed by the outside world, but can only be accessed indirectly through the public method get/set
  2. The constructor of the parent class cannot inherit, and the subclass can be accessed using the super keyword
  3. If the member variables of the child class are consistent with those of the parent class, the principle of proximity shall be followed
  4. If the subclass inherits from the parent class, the default access is * * parameterless construction * * (Zi Zi = new Zi();). If you need to access a parameterized construct, you need to add specific parameters to () after the new object.
  5. The subclass will certainly use the attribute method of the parent class, so super () is hidden in the first line of the subclass's construction method; Initialize data for the parent class first.
  6. If the parent class has no constructor, all constructors of the child class will report errors

3.7 shortcomings in inheritance

  1. Reduce code flexibility. Subclasses must have the properties and methods of the parent class, so that there are more constraints in the free world of subclasses;
  2. Enhanced coupling. When the constants, variables and methods of the parent class are modified, the modification of the child class needs to be considered, and in the absence of specifications, this modification may lead to very bad results - a large piece of code needs to be modified.

3.8 method rewriting and method overloading

  1. Method overloading: 1) method names are consistent; 2) Different formal parameter lists (number and type)
  2. Method rewrite: as like as two peas, the subclass has the same method declaration as the parent class.
  3. Purpose of Rewriting: the subclass has its own function, and the function of the parent class needs to be overwritten!

4: Polymorphism

Polymorphism is a kind of transaction that reflects different forms at different times, which is called polymorphism.

4.1 prerequisites for polymorphism

  1. Extensions with inheritance
  2. Override of existing method is required
  3. Must be a parent class pointing to a child class object

4.2 format

Inheritance up:
Format: Fu fu = new Zi();
Downward inheritance: if the parent class wants to use the methods of the child class, it needs downward transformation
Format: Zi = (Zi) Fu;
Polymorphism (ClassCastException exception will occur if downward transformation is not used properly)

4.3 characteristics of polymorphism

  1. Access to member variables: compile and run
  2. Access to member methods: compile and run
  3. If the member method is a static static method: compile and run on the left
  4. Constructor: you need to initialize the constructor of the parent class before initializing the child class. Hierarchical initialization

4.4 benefits of polymorphism

  1. Improve code reuse (guaranteed by inheritance)
  2. Improved code extensibility (guaranteed by polymorphism)

4.5 keyword final in polymorphism

  1. Modified variable: after the variable is modified by fianl, it cannot be changed once assigned
  2. Modifier method: this method cannot be overridden
  3. Decorated class: this class cannot be inherited (the address value of this class object will not change)
 class People{
     private String name;
     private int age;
     private String gender;
     final String nationality ="China";
     public People(){}

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

     public String getName() {
         return name;
     }

     public void setName(String name) {
         this.name = name;
     }

     public int getAge() {
         return age;
     }

     public void setAge(int age) {
         this.age = age;
     }

     public String getGender() {
         return gender;
     }

     public void setGender(String gender) {
         this.gender = gender;
     }

     //Unique method
     public static void eat(){}

     public void sleep(){}

     public final void study(){
         System.out.println("study");
     }
 }
 class student extends People{
     public student() {}

     public student(String name, int age, String gender) {
             super(name, age, gender);
     }

     @Override
     public void sleep() {
         System.out.println("This is a subclass of sleep");
     }
     public void goToSchool(){
         System.out.println(this.getName()+getAge()+"year"+getGender()+super.nationality+"Go to school");
     }
 }
 //Test class
public class finalDemo {
    public static void main(String[] args) {
//        Data initialization is carried out through parametric construction, and the parent class points to the child class object.
//        Upward transformation
        People p  = new student("student" ,35 , "female");
        p.sleep();
//        Transition down to access subclass specific methods
        student s= (student)p;
        s.goToSchool();
    }
}

5: Abstract class

Summary description of a group in reality, such as Chinese - Shaanxi people - Xi'an people - Yanta people

5.1 abstract keyword: Abstract

This keyword can be applied to classes and methods

Format used in method:
Permission modifier (generally public) abstract return value type method name (formal parameter list)

Format used in class:
abstract class class name {}

5.2 characteristics of abstract classes

  1. Abstract classes do not necessarily have abstract methods, but one with abstract methods should be an abstract class
  2. Abstract methods do not have a method body. Inherited subclasses need to override the parent method to implement the method
  3. Abstract classes cannot be instantiated.
  4. Instantiation method of abstract class: the parent abstract class points to the subclass object. Fu fu =new Zi();

5.3 the purpose of the abstract method is

Force the subclass to override the parent method, and implement the specific function subclass. If the subclass does not override the abstract method of the parent class, the subclass will report an error. Non abstract methods do not need to be rewritten

//Parent class
public  abstract class people {
    private String name;
    private int age;
    private String gender;

    public people(){}

    public people(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public abstract void sleep();
}

//Teachers
public abstract class teacher extends people{
    private String occupation;//occupation

    public teacher() {
    }
    public teacher(String occupation) {
        this.occupation = occupation;
    }
    public teacher(String name, int age, String gender, String occupation) {
        super(name, age, gender);
        this.occupation = occupation;
    }
    public String getOccupation() {
        return occupation;
    }
    public void setOccupation(String occupation) {
        this.occupation = occupation;
    }
    @Override
    public void sleep() {
        System.out.println("Teachers also need to sleep");
    }
    public abstract void eat();
}
//High school teachers

public class highSchoolTeachers extends teacher {
    public highSchoolTeachers() {
    }
    public highSchoolTeachers(String occupation) {
        super(occupation);
    }
    public highSchoolTeachers(String name, int age, String gender, String occupation) {
        super(name, age, gender, occupation);
    }
    @Override
    public void eat() {
        System.out.println("High school teachers also need to eat");
    }
    public void selfIntroduction(){
        System.out.println("hello everyone! I am:"+getName()+"\n"+"this year"+getAge()+"Years old. My profession is"+"\""+
                getOccupation()+"\"");
    }
}
//Test class
public class testDemo {
    public static void main(String[] args) {
        teacher t = new highSchoolTeachers("Gao Yuanyuan", 32, "female", "High school teacher");
        t.sleep();
        t.eat();
        //Downward transformation calls subclass specific methods
        highSchoolTeachers h= (highSchoolTeachers)t;
        h.selfIntroduction();
    }
}

Topics: Java