Object oriented -- static/final / code block / abstraction / interface / internal class

catalogue

1 keyword: static

2 understand the syntax of main method

Class 3 member 4: code block

4 keyword: final

5 abstract classes and abstract methods

6 interface

Five members of class 7: internal class

static

function

  1. Meaning: static

  2. It can be used to modify attributes, methods, code blocks and internal classes

  3. Use static to modify attributes: indicates static variables (class variables). Those without static are instance variables. If multiple objects of a class are created and multiple objects share the same static variable, modifying a static variable through an object will cause other objects to call the static variable

Other descriptions of static variables:

  • Static variables are loaded with the loading of the class, which is earlier than the creation of the object. Like the class, they are loaded only once, and there is a copy in memory
  • It can be called through class. Static variables, but instance variables cannot be called in this way
  • Memory resolution:
  1. Static methods: similar to static variables, they can be called between classes. With class loading, only static methods or attributes can be called. For non static methods, either non static methods or attributes or static methods or attributes can be called
  2. Note:
  • this keyword and super keyword cannot be used in static methods
  • The use of static attributes and static methods can be understood from the perspective of life cycle
  1. How to determine whether a property should be declared as static during development?
  • If the attribute can be shared by multiple objects, it will not vary with different objects, such as the interest rate attribute in the bank account class

  • Constants in classes are also often declared as static

      In development, how to determine whether a property should be declared as static´╝č
    
  • The method to manipulate static properties is usually set to static

  • The method in the tool class is customarily declared as static. For example, Math, Arrays and Collections can directly call methods with classes without a new object

application

class Circle{
    private double radius;
    private int id;
    
    public Circle(){
    	id=init++;//You can automatically generate continuous IDS each time you create them
   		total++;
	}
    public Circle(double radius){
    	this();//Call the above constructor once without repeating
        this.radius=radius;
	}
	private static int init=1001;
    private static total;
}

Singleton design pattern

Take certain methods to ensure that there is only one object instance of a class in the whole software system, and the class only provides a method to obtain its object instance

Hungry Han style

public class SingletonTest1{
    public static void main(String[] args){
    Bank bank1=Bank.getInstance();    
    Bank bank2=Bank.getInstance(); //At this time, bank1==bank2 is established   
    }
}
class Bank{
    //1. Constructor of privatization class
    private Bank(){
        
    }
    //2. Create an object of class internally, which is required to be declared as static
    private static Bank instance=new Bank();
    //3. Provide public methods to return class objects
    public static Bank getInstance(){
        return instance;
    }
}

Lazy style

public class SingletonTest1{
    public static void main(String[] args){
    Order order1=Bank.getInstance();    
    Order order2=Bank.getInstance(); //At this time, bank1==bank2 is established   
    }
}
class Order{
    //1. Constructor of privatization class
    private Order(){
        
    }
    //2. Create an object of class internally, which is required to be declared as static
    private static Order instance=null;
    //3. Provide public methods to return class objects
    public static Order getInstance(){
        if(instance==null){
            instance=new Order();
        }
        return instance;
    }
}

Distinguish between hungry and lazy

Hungry Chinese style: the object loading time is too long (disadvantage), which is thread safe (advantage)

Lazy: delay the creation of objects (advantages). The current writing method is not thread safe. It can be modified when multithreading content

Usage scenario

Only one instance is generated, which reduces the system performance overhead. When the generation of an object requires more resources, a singleton object can be directly generated and permanently resident in memory

  1. Site counters to ensure synchronization
  2. The log application of the application, because the log file is generally open all the time, so it is easy to append
  3. Database connection pool. One pool can make n connections at the same time, and one connection pool is fixed
  4. Class to read configuration file
  5. Application class
  6. windows Task Manager, recycle bin, etc

Understand the use of main method

  1. The main() method serves as an entry to the program
  2. main() is also a normal static method
  3. It can be used as a way for us to interact with the console. Previously, Scanner was used

Class member 4: code block

This is equivalent to one more method for attribute assignment. In fact, it is not used frequently

  1. Code block function: used to initialize classes and objects
  2. If the code block is decorated, you can only use static
  3. Classification: static code block non static code block
  4. Static code block:
  • There can be output statements inside
  • Execute as the class is loaded;
  • Information for initializing classes;
  • If multiple static code blocks are defined in a class, they are executed in the order of declaration;
  • The execution of static code blocks takes precedence over the execution of non static code blocks
  1. Non static code block:
  • There can be output statements inside
  • Executes as the object is created (new)
  • Execute every time you create an object
  • The function is to initialize the properties of the object when creating the object
  • If multiple non static code blocks are defined in a class, they are executed in the order of declaration
  1. Execution order of attribute assignment

Default initialization -- explicit initialization / assignment in code block -- initialization in constructor -- object. Attribute or object. Method assignment

final keyword

  1. final can modify structures: classes, methods, and variables
  2. final class: this class cannot be inherited by other classes, such as String, System and StringBuffer
  3. final method: cannot be overridden, such as getClass in Object
  4. final variable: the variable at this time is called a constant and cannot be changed
  • The allowed assignment positions are: display initialization, initialization in code block and initialization in constructor
  1. Final local variable: especially when final is used to modify a formal parameter, it indicates that the formal parameter is a constant. When this method is called, the formal parameter is assigned a value. After that, it can only be used in the method and cannot be re assigned
  2. static final modifier attribute: global constant. All attributes in the interface are global constants
  3. Usage: General methods are rarely used, and properties sometimes need final

Abstract classes and abstract methods

abstract means abstract. It is used to modify structures, classes and methods

abstract class

Abstract modifier class: abstract class. This class cannot be instantiated

  • There must be a constructor in the abstract class, which is convenient for calling when subclass instantiation
  • Subclasses are generally provided in development

Abstract method

  • Only the method declaration, no method body
  • The class containing abstract methods must be an abstract class, but there can be no abstract methods in an abstract class
  • If a subclass overrides all abstract methods of the parent class, the subclass can be instantiated
abstract class Person{
    public abstract void eat();
}

Precautions in use

  • abstract cannot be used to modify structures such as attributes and constructors
  • Cannot be used to modify private methods, static methods, and final methods

Creates an anonymous subclass of an abstract class

//Person is defined as an abstract class, and Worker/Student is a subclass of person
Worker worker=new Worker();
method(worker);//Non anonymous class non anonymous object

method(new Student()); //Non anonymous class anonymous object

//A non anonymous object of each anonymous subclass is created: p
Person p=new Person(){
    @override
    public void eat(){//Subclasses of abstract classes must override the abstract methods in them
        
    }
} 
//Create anonymous objects of anonymous subclasses
method(new Person(){
    @override
    public void eat(){//Subclasses of abstract classes must override the abstract methods in them
        
    }
})

Template method design pattern

public class TemplateTest{
    SubTemplate t=new SubTemplate();
    t.spendTime();
}
abstract class Template{
    //Calculate the time spent executing a piece of code
    public void spendTime(){
        long start=System.currentTimeMillis();
        code();//Uncertain and changeable parts
        long end=System.currentTimeMillis();
        System.out.println("Time spent is"+(end-start));
    }
    public abstract void code();
}
class SubTemplate extends Template{
    @override
    public void code(){
		System.out.println("sss");
        })
    }
}

Interface

  • Sometimes you need to derive a subclass from several classes. java does not support multiple inheritance, and classes cannot meet this condition.
  • Sometimes it is necessary to extract common behavior features from several classes, but there is no is-a relationship, but there are the same behavior features. For example, college students and middle school students are students, hurdlers and basketball players are athletes. They all have learning skills. On the one hand, they already have a parent class, on the other hand, they do not meet the relationship between child and parent class with skills. Therefore, skills can be defined as interfaces

Use of interfaces

  1. Interfaces are defined using interface s

  2. In java, interface and class are two parallel structures

  3. How to define an interface: define members in an interface

    3.1 JDK7 and before: only global constants and abstract methods can be defined in the interface

    Global constant: public static final (even if these words are omitted, they are still global constants)

    Abstract method: public abstract (even if these words are omitted, it is still an abstract method)

    Constructor cannot be defined in interface!! This means that the interface cannot be instantiated

    3.2 after jdk8, static methods and default methods can be defined in addition to global constants and abstract methods

  4. In Java development, interfaces are used by methods that let classes implement

    If the implementation class overrides all abstract methods in the interface, the implementation class can be instantiated

    If not all abstract methods are overridden, the implementation class remains abstract

  5. java classes can implement multiple interfaces, breaking the limitation of single inheritance of classes. Multiple interfaces can be implemented with implements a and B

  6. Interfaces can inherit from one interface to another, and multiple interfaces can inherit

  7. The specific use of the interface reflects the polymorphism, and the interface can actually be regarded as a specification

package com.atguigu.ex1;

public class test {
	 
}
interface Flyable{
	public static final int MAX_SPEED=7900;
	int MIN_SPEED=7900;
	public abstract void fly();
	void stop();
}
//Overriding all abstract methods can be instantiated
class plane implements Flyable{
	@Override
	public void fly() {
		System.out.println("take off");
		
	}
	@Override
	public void stop() {
		System.out.println("stop it");
		
	}
}
//Not overridden. All abstract methods must be abstract classes
abstract class Kite implements Flyable{
	@Override
	public void fly() {
		// TODO Auto-generated method stub
		
	}
}
//Multiple inheritance between interfaces
interface AA{
	
}
interface BB{
	
}
interface CC extends AA,BB{
	
}

proxy pattern

Application scenario:

Security proxy: block direct access to real roles

Remote proxy: handle remote method calls through proxy classes

Delayed loading: load the lightweight proxy object first, and then the real object

Classification:

Static proxy

Dynamic agent

Factory design mode

It realizes the separation of creator and caller, that is, shielding the specific process of creating objects, so as to improve flexibility

The simple factory mode defines a factory class XXXFactory that implements class objects, including getXXX and other functions. However, when adding products, the existing code needs to be modified, which violates the opening and closing principle

The factory method pattern defines a factory interface, and N factory classes implement the factory interface

New features of Java 8 interface

In addition to defining global constants and abstract methods, you can also define static methods and default methods

Static method

1. Static methods defined in the interface can only be called through the interface

2. By implementing the object of the class, you can call the default method in the interface

3. If the method with the same name and parameter is declared in the inherited parent class and the implemented interface of the subclass (or implementation class), the method of the parent class will be called by default when the subclass is not overridden (class priority principle)
However, duplicate names are not allowed for attributes

4. If the implementation class implements multiple interfaces and the default method with the same name and parameter is defined in multiple interfaces, an error will occur if the implementation class does not override this method (interface conflict), so it is necessary to override this method in the implementation class

public class SubclassTest {
	public static void main(String[] args) {
		Subclass s=new Subclass();
		//s.method1();  An error will be reported when calling the implementation class of the interface
		//1. Static methods defined in the interface can only be called through the interface
		CompareA.method1();
		//2. By implementing the object of the class, you can call the default method in the interface
		s.method2();
		s.method3();
	}
}
package com.atguigu.ex1;
public interface CompareA{
	public static void method1() {
		System.out.println("method1");
	}
	public default void method2() {
		System.out.println("method1");
	}
	default void method3() {
		System.out.println("method1");
	}
}

Inner class

A class defined inside another class is called an internal class, otherwise it is an external class

  1. The internal class is generally used in the class or statement block that defines it. The complete name must be given when referring to the external class
  2. Internal class classification: member internal classes (static and non static) local internal classes (within methods, code blocks, constructors)
  3. Member inner class: a structure that can call an outer class; You can define attributes, methods, constructors, etc; It can be modified by final and abstract

Focus on three issues:

  1. How to instantiate an object of a member's inner class
		//Create a static member inner class of the Brain instance
		Person.Brain br=new Person.Brain();
		//Create non static member inner class of Eye instance
		Person person=new Person();
		Person.Eye eye=person.new Eye();
  1. How to distinguish the structure of calling external classes in member internal classes

If Person has an internal class Brain, and the name attribute is defined, and a method parameter in Brain is name, then

name parameter

In this.name brain class

Person.name in person

  1. Use of internal classes in development

Interview question: similarities and differences between abstract classes and interfaces

Similarities:

  • Cannot instantiate
  • Can be inherited

difference:

  • Abstract classes have constructors. Interfaces cannot declare constructors
  • Abstract classes can only inherit single, and interfaces can inherit multiple

Tags: Java

Posted on Sun, 28 Nov 2021 05:00:57 -0500 by djbuddhi