Han Shunping learned Java in 30 days with zero foundation [Chapter 8 Object-Oriented Programming (Advanced)]

class variable

P373~P423

Class variables are also called static variables

Static variables are shared by all objects of the same class

Static variables are generated when the class is loaded

How to define class variables

访问修饰符 static 数据类型 变量名;

How to access class variables

  • classname.classvariablename
  • object-name.class-variable-name

The access rights and scope of access modifiers for static variables are the same as for ordinary properties

Class variable usage details

When we need to let all objects of a certain class share a variable, we can consider using class variables

class method

访问修饰符 static 数据返回类型 方法名(){}

class method call

  • class name. class method name
  • object name.class method name

class method use case

When the method does not involve any object-related members, the method can be designed as a static method to improve development efficiency.

If we don't want to create an instance, we can also call a method. At this time, it is very appropriate to make the method a static method

For example: the method in the tool class

Math class, Arrays class, Collections collection class

Class Method Considerations

  • Both class methods and ordinary methods are loaded with the loading of the class, and the structural information is stored in the method area. There is no this parameter in the class method, and the this parameter is implied in the ordinary method
  • Class methods can be called by class name or by object name
  • Ordinary methods are related to objects and need to be called by object name
  • Object-related keywords such as this and super are not allowed in class methods
  • Only static variables or static methods can be accessed in class methods
  • Ordinary member methods can access both non-static members and static members

main method

public static void main(String[] args){}

  1. public: The java virtual machine needs to call the main() method of the class, so the access permission of this method must be public
  2. static: The java virtual machine does not have to create an object when executing the main() method, so the method must be static
  3. This method accepts an array parameter of Sting type, which stores the parameters passed to the running class when executing the java command

Notice

In the main method, you can directly call the static method or static property of the class where the main method is located

However, you cannot directly access the non-static members of the class. You must create a strength object of the class before you can access the non-static members of the class through this object.

code block

A code block is also called an initialization block, which belongs to a member of a class and is similar to a method. It encapsulates logic statements in the method body and surrounds them with {}.

But unlike a method, there is no method name, no return, no parameters, only the method body, and it does not need to be explicitly called through the object or class, but implicitly called when the class is loaded, or when the object is created

basic grammar

[修饰符]{
  代码
};

Notice

  1. The modifier is optional, but it can only be static when written
  2. Code blocks are divided into two categories, static modified called static code blocks, no static modified called ordinary code blocks
  3. The logic statement can be any logic statement (input, output, method call, loop, judgment)
  4. The semicolon can be written or omitted

understand

  1. It is equivalent to another form of constructor (a supplementary mechanism to the constructor), which can perform initialization operations
  2. If there are repeated statements in multiple constructors, they can be extracted into the initialization block to improve code reusability
  3. No matter which constructor is called to create the object, the content of the code block will be called first
  4. The order of code block calls takes precedence over constructors

Code Block Usage Details, com.codeBlock.CodeBlockDetail.java

  1. The static code block is also called the static code block. It is used to initialize the class and execute it as the class is loaded, and it will only be executed once. If it is an ordinary code block, create an object and execute it once.
  2. when the class is loaded
    1. When an object instance is created (new)
    2. Create a subclass object instance, the parent class will also be loaded, and the parent class is loaded first, and the subclass is loaded later
    3. When using static members of a class (static properties, static methods)
  3. Ordinary code blocks are called implicitly when an object instance is created. Once created, it will be called once, which is equivalent to the supplement of the constructor. If you just use the static members of the class, the normal code block will not be executed.
  4. When creating an object, the calling sequence in a class is:
    1. Call static code block and static attribute initialization (note: static code block and static attribute initialization call have the same priority, if there are multiple static code blocks and multiple static variable initialization, they will be called in the order in which they are defined)
    2. Call the initialization of ordinary code blocks and ordinary attributes (note: the priority of ordinary code blocks and ordinary attribute initialization calls is the same, if there are multiple ordinary code blocks and multiple ordinary attribute initializations, they will be called in the order of definition)
    3. call constructor
  5. The front of the constructor actually implies super() and calls ordinary code blocks. Static code blocks and attribute initialization are executed when the class is loaded, so they are executed prior to constructors and ordinary code blocks. CodeBlockDetail03.java
  6. When creating a subclass, static code blocks, static property initialization, common code blocks, normal property initialization, and the calling order of the constructor are as follows:
    1. Static code block of the parent class, static property initialization
    2. Static code block of subclass, static property initialization
    3. Common code block of the parent class, normal property initialization
    4. parent class constructor
    5. Normal code block for subclasses, normal initialization
    6. subclass constructor
  7. Static code blocks can only call static members directly, and ordinary code blocks can call any members
package com.codeBlock;

public class CodeBlockDetail {
    public static void main(String[] args) {
        //1. static代码块也叫静态代码块,作用是对类进行初始化,且随着类的加载而执行,并且只会执行一次。
        //如果是普通代码块,每创建一个对象,就执行。
        //2. 类什么时候被加载
            //1. 创建对象实例时(new)
            //2. 创建子类对象实例,父类也会被加载
//        AA aa = new AA();   // bb的静态代码块被执行
                             // aa的静态代码块被执行
                             // bb的普通代码块
            //3. 使用类的静态成员时(静态属性,静态方法)
//        System.out.println(Cat.name);   //cat的静态代码块被执行
                                            //mao
        //3. 普通的代码块,在创建对象实例时,会被隐式的调用。被创建一次,就会调用一次。
        //如果只是使用类的静态成员,普通代码块并不会执行。
//        BB.show();    //bb的静态代码块被执行
                        //调用静态属性,普通代码块不调用
//        BB bb1 = new BB();  //bb的静态代码块被执行
                            //bb的普通代码块
    }
}

class BB {
    static {
        System.out.println("bb的静态代码块被执行");
    }
    {
        System.out.println("bb的普通代码块");
    }

    public static void show() {
        System.out.println("调用静态属性,普通代码块不调用");
    }
}

class AA extends BB {
    static {
        System.out.println("aa的静态代码块被执行");
    }
}
class Cat{
    public static String name="mao";
    static {
        System.out.println("cat的静态代码块被执行");
    }
}

Design Patterns

what is design pattern

  1. Classic use of static methods and properties
  2. Design patterns are the preferred code structure, programming style, and problem-solving way of thinking after summarizing and theorizing in a large number of practices.

singleton pattern

  1. The so-called singleton design pattern of a class is to adopt a certain method to ensure that in the entire software system, there can only be one object instance for a certain class, and this class only provides a method to obtain its object instance.
  2. There are two ways of singleton mode: hungry man style and lazy man style

Singleton pattern application example

[Hungry Chinese Style], com.single_.SingleTon01.java

As long as the class is loaded, this object will be created. It may just use the class variable. Even if it is not used, this object will be created together, which will waste resources.

step:

  1. Constructor privatization: prevent direct new

  2. object created inside the class

  3. Expose a static public method. getInstance

    (Why static? Because if you want to call the class method directly without creating an instance, it is static, and the properties in the method are also static)

    (If getInstance is called multiple times and received with different variable names, it actually points to the same object, because static properties will only be initialized once)

  4. Code

public class SingleTon01 {
    public static void main(String[] args) {
//        GirlFriend xiaohong = new GirlFriend("xiaohong");
//        GirlFriend xiaobai = new GirlFriend("xiaobai");
        GirlFriend instance = GirlFriend.getInstance();
        System.out.println(instance);
    }
}

class GirlFriend {
    private String name;
    //如何保证只能有一个girlfriend
    //步骤:
    //1、构造器私有化
    //2、类的内部创建
    private static GirlFriend gf = new GirlFriend("xiaohong");
    private GirlFriend(String name) {
        this.name = name;
    }
    //3、提供一个公共静态方法
    public static GirlFriend getInstance() {
        return gf;
    }
    @Override
    public String toString() {
        return "GirlFriend{" + "name='" + name + '\'' + '}';
    }
}

[Lazy style], com.single_.SingleTon02.java

Only when the user calls the getInstance method will the object be created, and if this method has been called, when it is called again, the object created last time will be returned

public class SingleTon02 {
    public static void main(String[] args) {
        System.out.println(Cat.getInstance());
    }
}
//希望程序运行过程中只能创建一个Cat
class Cat{
    private String name;
    private static Cat cat;
    //1、构造器私有化
    //2、定义一个static属性对象
    private Cat(String name) {
        this.name = name;
    }
    //3、提供公共static方法,返回cat对象
    
    public static Cat getInstance(){
        if(cat==null){
            cat= new Cat("xiaomao");
        }
        return cat;
    }

Difference Between Hungry Man Style and Lazy Man Style

  1. The main difference between the two lies in the timing of creating objects. The hungry style creates an object instance when the class is loaded, while the lazy style creates it when it is used.
  2. There is no thread safety problem in the hungry style, but there is a thread safety problem in the lazy style (see thread learning)
  3. There is a possibility of wasting resources in the hungry style, because if the programmer does not use an object instance, the object created by the hungry style will be wasted, and the lazy style is created when it is used, so there is no such problem
  4. In the javaSE standard class, java.lang.Runtime is the classic singleton pattern
public class Runtime {
    private static Runtime currentRuntime = new Runtime();
    public static Runtime getRuntime() {
        return currentRuntime;
    }
    /** Don't let anyone else instantiate this class */
    private Runtime() {}
    }

final keyword

final can modify classes, properties, methods and local variables

Usage: com.final_.Final01.java

  1. When you do not want the class to be inherited, you can use final modification
  2. When you do not want a method of the parent class to be overwritten/overridden by the subclass [access modifier final return type method name]
  3. When you do not want the value of an attribute of the class to be modified [public final double TAX_RATE=0.08]
  4. When you do not want a local variable to be modified [final double TAX_RATE=0.08]
package com.final_;
public class Final01 {
    public static void main(String[] args) {
        A a = new A();
        a.TAX_RATE=0.09;
    }
}
//如果要求A不能被其他类继承,使用final修饰A
//final class A{
class A{
    //    不希望类的某个属性的值被修改
//    public final double TAX_RATE=0.08;
    public double TAX_RATE=0.08;


    //    不希望方法被子类覆盖
//    public final void hi(){}
    public void hi(){
        //    不希望某个局部变量被修改
//        final int money=100;
        int money=100;
        money =101;
    }
}

class B extends A{
    @Override
    public void hi() {
        super.hi();
    }
}

final details

  1. Final modified properties are also called constants, named with XX_XX_XX
  2. The final modified attribute must be assigned an initial value when it is defined, and can no longer be modified. The initial value can be assigned in the following positions:
    1. when defined
    2. in the constructor
    3. in the code block
class AA{
  public final double TAX_RATE=0.08;//定义时
  public final double TAX_RATE2;
  public final double TAX_RATE3;
  public AA(){//构造器中赋值
    TAX_RATE2=1.1;
  }
  {//代码块赋值
    TAX_RATE3=8.8;
  }
}
  1. If the final modified property is static, the initialization position can only be
    1. when defined
    2. static block
class BB{
  public static final double TAX_RATE=0.08;//定义时
  public static final double TAX_RATE2;
  static {//代码块赋值
    TAX_RATE3=8.8;
  }
}
  1. Final classes cannot be inherited, but objects can be instantiated
  2. If the class is not a final class but contains a final method, the method cannot be overridden but can be inherited
  3. Generally speaking, if a class is final, there is no need to write the method as final.
  4. final cannot modify the constructor
  5. Final and static are often used together, which is more efficient and will not cause class loading. The underlying compiler has optimized com.final_.FinalStatic.java
package com.final_;
public class FinalStatic {
    public static void main(String[] args) {

        System.out.println(AA.name);
    }
}

class AA {
    public static final String name = "aaa";
    static {
        System.out.println("静态代码块");
    }
}

  1. Wrapper classes (Integer, Double, Float, Boolean are all final), String is also a final class

abstract class

com.abstract_.Abstract01.java

When some methods of the parent class need to be declared, but you are not sure how to implement them, you can declare them as abstract methods, then this class is an abstract class

package com.abstract_;

public class Abstract01 {
    public static void main(String[] args) {

    }
}

abstract class Animal {
    private String name;
    public Animal(String name) {
        this.name = name;
    }

    //eat实现了,但没什么意义
    //出现了父类方法不确定性的问题
    //考虑将该方法设计为抽象方法
    //所谓抽象方法就是没有实现的方法
    //所谓没有实现就是没有方法体{}
    //当一个类中存在抽象方法时,需要将该类声明为abstract类
    //一般来说,抽象类会被继承,由其子类来实现抽象方法
    public abstract void eat();
}

introduce

  1. When a class is modified with the abstract keyword, the class is called an abstract class

    访问修饰符 abstract 类名{}

  2. When the abstract keyword is used to modify a method, the method is an abstract method without a method body {}

    访问修饰符 abstract 返回类型 方法名(参数列表);

  3. The value of the abstract class lies more in the design. After the designer designs it, let the subclass inherit and implement the abstract class

abstract class details

  1. Abstract classes cannot be instantiated
  2. An abstract class does not necessarily contain an abstract method, that is to say, an abstract class may not have an abstract method
  3. But if the class contains abstract methods, the class must be declared as abstract
  4. abstract can only modify classes and methods, not attributes and others
  5. An abstract class can have arbitrary members, because an abstract class is still a class
  6. An abstract method cannot have a method body {}
  7. If a class inherits an abstract class, it must implement all the abstract methods of the abstract class, unless it is itself an abstract class
  8. Abstract methods cannot be decorated with private, final, and static, because these keywords are contrary to rewriting

Exercise, com.abstract_.AbstractExercise01.java

Write an Employee class, declared as an abstract class, containing three attributes: name, id, salary, and provide the necessary constructor and abstract method work(). For the Manager class, he is not only an employee, but also has bonus attributes. Please use the inheritance idea to design the CommonEmployee and Manager classes, and require the classes to provide necessary methods for attribute access and implement work(), "Manager, Common Employee name working..."

package com.abstract_;
public class AbstractExercise01 {
    public static void main(String[] args) {
        CommonEmployee xiaoming = new CommonEmployee("小明", 101, 1000);
        Manager daming = new Manager("大明", 99, 1100, 2000);
        xiaoming.work();
        daming.work();
    }
}
abstract class Employee {
    private String name;
    private int id;
    private double salary;
    public Employee(String name, int id, double salary) {
        this.name = name;
        this.id = id;
        this.salary = salary;
    }
    public String getName() {return name;}
    public void setName(String name) {this.name = name;}
    public int getId() {return id;}
    public void setId(int id) {this.id = id;}
    public double getSalary() {return salary;}
    public void setSalary(double salary) {this.salary = salary;}
    public abstract void work();
}
class Manager extends Employee {
    private double bonus;
    public Manager(String name, int id, double salary, double bonus) {
        super(name, id, salary);
        this.bonus = bonus;
    }
    public double getBonus() {return bonus;}
    public void setBonus(double bonus) {this.bonus = bonus;}
    @Override
    public void work() {
        System.out.println("经理 " + getName() + "工作中..");
    }
}
class CommonEmployee extends Employee {
    public CommonEmployee(String name, int id, double salary) {
        super(name, id, salary);
    }
    @Override
    public void work() {
        System.out.println("普通员工" + getName() + "工作中..");
    }
}

interface

The interface is to give some unrealized methods, encapsulate them together, and write out these methods according to the specific situation when a certain class needs to use them.

interface 接口名{
//属性
//方法(1抽象方法2默认方法3静态方法)
}
class 类名 implements 接口名{
  自己属性;
  自己方法;
  必须实现接口的抽象方法
}

Before JDK7.0, all methods in the interface have no method body

After JDK8.0, interface classes can have static methods that need static modification, and default methods need default modification, which means that interfaces can have specific implementations of methods

Quick Start, com.interface_.Interface01.java

package com.interface_;

public class Interface01 {
    public static void main(String[] args) {
        Computer computer = new Computer();
        Camera camera = new Camera();
        Phone phone = new Phone();
        computer.work(camera);
        computer.work(phone);
    }
}
interface UsbInterface {
    public void start();
    public void stop();
}

class Computer {
    public void work(UsbInterface usbInterface) {
        usbInterface.start();
        usbInterface.stop();
    }
}

class Camera implements UsbInterface {
    @Override
    public void start() {
        System.out.println("我是相机,开始工作");
    }

    @Override
    public void stop() {
        System.out.println("我是相机,结束工作");
    }
}

class Phone implements UsbInterface {
    @Override
    public void start() {
        System.out.println("我是手机,开始工作");
    }

    @Override
    public void stop() {
        System.out.println("我是手机,结束工作");
    }
}

interface details

  1. interface cannot be instantiated

  2. All methods in the interface are public methods, and abstract methods in the interface do not need to be modified by abstract

  3. A common class implements interface must implement all methods of the interface

  4. The abstract class implements interface, you don't need to implement the method of the interface

  5. A class can implement multiple interfaces at the same time

  6. The properties in the interface can only be final, and they are public static final. For example, int a=1; is actually public static final int a=1;

  7. The access form of the attribute in the interface: interface name. attribute name

  8. An interface cannot inherit from other classes, but it can inherit from multiple other interfaces

    interface extends B,C{}

  9. Interface modifiers can only be public and default, the same as class modifiers

Implementing Interfaces vs Inheriting Classes

Interfaces and inheritance solve different problems

  • The value of inheritance lies in: solving code reusability and maintainability
  • The value of the interface lies in: design, design various specifications, and let other classes implement these methods

Interface achieves code decoupling to a certain extent

When to use abstract classes and interfaces

reference

When designing a class, first consider using the interface to abstract the characteristics of the class. When you find that some methods can be reused, you can use the abstract class to reuse the code. Simply put, interfaces are used to abstract the characteristics of things, and abstract classes are used for code reuse.

Of course, not all classes are designed from interfaces to abstract classes and then to classes. There is no absolute paradigm for programming to follow. Design according to your own needs.

Interface polymorphism

  1. Polymorphic parameters, InterfacePolyParameter.java
  2. Polymorphic array, InterfacePloyArr.java
  3. There is a polymorphic pass phenomenon in the interface, InterfacePolyPass.java

summary

Five members of a class: properties, methods, constructors, code blocks, inner classes

package 包名;
class 类名 extends 父类 implements 接口名{
  成员变量//属性
  构造方法//构造器
  成员方法//方法
  代码块
 }

inner class

Another class structure is completely nested inside a class. A class that is nested is called an inner class, and a class that nests other classes is called an outer class.

The biggest feature of inner classes is that they can directly access private properties, and can reflect the inclusion relationship between classes

basic grammar

class Outer{//外部类
  class Inner{//内部类
  }
}
class Other{//外部其他类
}

Classification of inner classes

Defined in the local position of the external class: such as in the method

  • Local inner class (with class name)
  • anonymous inner class (no class name)

Defined at the member position of the outer class:

  • Member inner class (not modified with static)
  • Static inner class (using static modification)

Defined locally in the outer class:

Local inner class, com.innerclass.LocalInnerClass.java

  • The local inner class is defined in the local position of the outer class, such as in the method, and has a class name
  • Cannot add access modifier, because his status is a local variable. Local variables cannot use modifiers, but can be modified with final
  • Scope: Only in the method or code block that defines it, it is equivalent to a local variable of type class
  • Local inner classes directly access outer class members, including private ones
  • The outer class needs to create an object and then access the inner class members
  • Other external classes cannot access local inner classes
  • If the external class and the local internal class have the same name, the principle of proximity is followed by default. If you absorb members of the external class from all parties, you can use the external class name.this.Member access
public class LocalInnerClass {
    public static void main(String[] args) {
    }
}

class Outer {
    private int n1 = 100;
    private void m2() {}
    private void m1() {
        // 局部内部类是定义在外部类的局部位置,比如方法中,并且有类名
        // 不能添加访问修饰符,因为他的地位就是一个局部变量。
        // 局部变量不能使用修饰符,但是可以用final修饰
        class Inner { // 局部内部类
            // 局部内部类可以直接访问外部类成员,包括私有的
            public void f1() {
                System.out.println("n1=" + n1);
            }
        }
    }
}

  1. A local inner class is defined in a method/code block
  2. Scope is in the method body/code block
  3. essence is a class

Anonymous Inner Class, com.anonymousInner.AnonymousInnerClass.java

An anonymous inner class is defined in a local location of the outer class, such as a method, and has no class name, and is still an object

An anonymous inner class is equivalent to implementing an interface or inheriting a parent class

Basic syntax for anonymous inner classes

new 类或接口(参数列表){
  匿名类类体
};

  1. An anonymous inner class is not only a class definition, but also an object, so from a grammatical point of view, it has both class characteristics and object creation characteristics, so anonymous inner class methods can be called
  2. Can directly access all members of the outer class, including private
  3. Cannot add access modifier, because his status is a local variable
  4. Scope: only in the method or code block that defines it
  5. Anonymous inner class directly accesses members of outer class
  6. Other external classes cannot access anonymous inner classes
package com.anonymousInner;
public class AnonymousInnerClass {
    public static void main(String[] args) {
        Outer04 outer04 = new Outer04();
        outer04.method();
    }
}
class Outer04 {//外部类
    private int n1 = 10;//属性
    public void method() {//方法
        //基于接口的匿名内部类
        //1、需求:想使用接口IA,并创建对象
        //2、传统方式:写一个类,实现该接口,然后创建对象
        //3、需求是Tiger类只使用一次,后面再不使用
//        IA tiger = new Tiger();
//        tiger.cry();
        //4、可以用匿名内部类来简化开发

        //演示基于接口的匿名内部类
        //tiger的编译类型:IA
        //tiger的运行类型:com.anonymousInner.Outer04$1
        //底层:class Outer04$1 implements IA{}
        IA tiger = new IA() {
            @Override
            public void cry() {
                System.out.println("老虎叫");
            }
        };
        tiger.cry();
        System.out.println("tiger的运行类型"+tiger.getClass());

        //演示基于类的匿名内部类
        //jack的编译类型:
        //jack的运行类型:com.anonymousInner.Outer04$2
        //底层:class Outer04$2 extends Father{}
        //和""Father jack = new Father("jack");"" 有区别,区别在于"{};",
        //实际是匿名内部类继承了Father类,应该是叫向上转型
        Father jack = new Father("jack") {};
        System.out.println("jack的运行类型"+jack.getClass());
    }
}
interface IA {
    public void cry();
}
// 传统方法:写一个类,实现该接口,然后创建对象
class Tiger implements IA {
    @Override
    public void cry() {
        System.out.println("老虎叫");
    }
}
class Father {
    public Father(String name) {super();}
    public void test() {}
}

Inner Class Exercise, com.anonymousInner.InnerClassExercise02.java

  1. There is a bell interface Bell, which has a ring method
  2. There is a mobile phone class Cellphone, which has the alarm clock function alarmclock, and the parameter is Bell type
  3. Test the alarm clock function of the mobile phone class, use the anonymous inner class as a parameter, and print: Lazy pig has woken up
  4. Then pass in another anonymous inner class and print: the little friend is in class
//1. 有一个铃声接口Bell,里面有个ring方法
//2. 有一个手机类Cellphone,具有闹钟功能alarmclock,参数是Bell类型
//3. 测试手机类的闹钟功能,通过匿名内部类作为参数,打印:懒猪起床了
//4. 再传入另一个匿名内部类,打印:小伙伴上课了
public class InnerClassExercise02 {
    public static void main(String[] args) {
        new Cellphone().alarmclock(new Bell(){
            @Override
            public void ring() {
                System.out.println("懒猪起床了");
            }
        });
        new Cellphone().alarmclock(new Bell() {
            @Override
            public void ring() {
                System.out.println("小伙伴上课了");
            }
        });
    }
}

interface Bell{
    public void ring();
}
class Cellphone{
    public void alarmclock(Bell bell){bell.ring();}
}

Defined at the member position of the outer class:

member inner class

  1. Can directly access all members of the outer class, including private
  2. You can add any access modifier public, protected, default, private, the status is equivalent to the member
  3. Scope: Like other members of the outer class, it is the entire class body
  4. Member inner class directly accesses outer class
  5. External class accesses internal class: create object in access
  6. External other classes access members of inner classes
  7. If the members of the outer class and the inner class have the same name, the inner class access will follow the principle of proximity by default. If you want to access the members of the outer class, you can use (outer class name.this.member) access

static inner class

The static inner class is defined in the member position of the outer class and has static modification

  1. Can directly access all static members of the outer class, including private ones, but cannot directly access non-static members
  2. Arbitrary access modifiers can be added
  3. Scope: Same as other members, for the entire class body
  4. Static inner class directly accesses outer class
  5. External class creates object to access static inner class

Guess you like

Origin blog.csdn.net/weixin_65656674/article/details/126416751