static,final, singleton design pattern and abstract (nanny notes)

 

catalogue

Static modifier

Static variable

Static and non static methods

Static code block

Anonymous code block

Singleton design pattern

Hungry Chinese implementation of singleton

Lazy implementation of singleton:

Video notes - Comparison between hungry and lazy:

final modifier

Decorated member variable - non static member variable:

Decorated member variable - static member variable:

final modifier reference variable

Interview questions

abstract class

Notes on template method design patterns

Static modifier

Static variable

Video note: when we write a class, we only describe the properties and behavior of the object. The object will be generated only through the new keyword. At this time, the system will allocate memory space to the object and its methods can be called externally. However, it is sometimes hoped that no matter how many objects are processed, there is only one copy of some specific data in the memory space. For example, many students belong to a school, so it is not necessary to allocate a variable representing the school name in each student's instance object.

Let's look at a piece of code

public class student {
	int age;
	static String name;
	public static void main(String[] args)
	{
  student a1=new student();
  student a2=new student();
  a1.age=10;
  a1.name="Xiao Ming";
  a2.age=20;
  System.out.println(a1.age);
  System.out.println(a2.age);
  System.out.println(a1.name);
  System.out.println(a2.name);
		
}
}

Although the attribute name of a2 is not assigned a value, the output result is the same as that of a1, which shows that there is only one static variable in memory for a class and can be shared by all instances of the class

public class student {
	int age;
	static String name;
	public static void main(String[] args)
	{
  student a1=new student();
  student a2=new student();
  a1.age=10;
  a1.name="Xiao Ming";
  a2.age=20;
  a2.name="Xiao Wang";
  System.out.println(a1.age);
  System.out.println(a2.age);
  System.out.println(a1.name);
  System.out.println(a2.name);
		
}
}

 

When A2 When name is assigned, A1 Name also changed

Instance variable: when modifying a non static attribute in an object, the same attribute in other objects will not be changed

Static variable: multiple objects share the same static variable

  • Static variables are loaded with the loading of the class, and can be called through class. Static variables
  • Static variables are loaded before objects are created
  • Since the class is loaded only once, only one copy of the static variable is saved in memory and exists in the static field of the method area

Static and non static methods

Static method " may not " Direct access to non static variables and non static methods in a class , however " sure " Direct access to static variables and static
method
be careful :this and super Non static variables in a class .( Cannot be used in static methods )
public class student {
	int age;
	static String name;
	public void a() {}
	public static void b() {}
	public static void test()
	{
		System.out.println(age);//Compilation error
	}
}

 

If it is changed to name, the compilation passes

When static is removed and is a non static method

Non static methods "can" directly access non static variables and non static methods in a class, or "can" directly access static variables and static methods in a class
A static method of a parent class can be inherited by a subclass, but cannot be overridden by a subclass
public class student {
	int age;
	public static void b() {}
}
public class studentA extends student//Inherit parent class
{
public void b()//Compilation error
{
	System.out.println(this.age);
}
}

When inheriting but not rewriting

public static void main(String[] args)
{
studentA A=new studentA();
A.b();
} 	

Compilation passed, but not rewritten

A non static method of a parent class cannot be overridden as a static method by a child class

public class student {
	int age;
	public  void b() {}
}
public class studentA extends student//Inherit parent class
{
	public static void b();//Compilation error
}

Static code block

static{

}
Static code blocks are automatically executed after the class is loaded , and execute it only once
effect : static code blocks are used to initialize and assign values to static member variables in a class
public class student {
	public static int age;
	static
	{ 
		age=1;
	}
	public  void b() {
		age=2;
	}
	public static void main(String[] args)
	{
     System.out.println(student.age);
    }
}

Video notes:

Assign a value to a static variable in the constructor , There is no guarantee that the assignment will succeed , Because the constructor points to the object when it is created , however Static variables can be accessed directly using the class name without creating an object
The display assignment of non static attributes in subclasses is after the execution of the parent class constructor and before the execution of anonymous code blocks in subclasses

Anonymous code block

public class s{
{
 //Anonymous code

}
}
Video note: because there is no name , These code blocks cannot be actively called in the program.
Anonymous code blocks are automatically executed when objects are created , And before the constructor executes. At the same time, anonymous code blocks are automatically executed every time an object is created
public class student {
private int age;
	public student()
	{
		System.out.println("student constructor ");
		test();
	}
	public void test()
	{
		System.out.println("student  test method:age="+age);
	}
}
public class studentA extends student//Inherit parent class
{
private int age=10;
	{
		System.out.println("Subclass anonymous code block");
	}
	static {
		System.out.println("Subclass static code block");
	}
	public studentA()
	{
		System.out.println("Subclass constructor");
	}
	public void test()
	{
		System.out.println("Subclass studentA test method:age="+age);
	}
public static void main(String[] args)
{
	new studentA();
} 	
}

The display assignment of non static attributes in subclasses is after the execution of the parent class constructor and before the execution of anonymous code blocks in subclasses

Pithy formula: father and son, static first

Video notes:

  1. Function of code block: used to initialize classes and objects.
  2. If the code block is decorated, only static can be used.
  3. Classification: static code block and non static code block
  4. Static code block
  • There can be output statements inside
  • Executes as the class loads, and only once
  • Function: initialize class information
  • 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
  • Static code blocks cannot call non static structures

Non static code block

  • There can be output statements inside
  • Executes as the object is created
  • Each time an object is created, a non static block of code is executed
  • Function: you can 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
  • Non static code blocks can call non static attributes, static methods, or non static attributes, non static methods

Singleton design pattern

Definition: take certain methods to ensure that there can only be one object instance for a class in the whole software system.  

Hungry Chinese implementation of singleton

  1. Privatization constructor
  2. An object that creates a class internally
  3. Provides a public method that returns the object of the class
  4. It is required that this object must also be declared static
public class demo{
	public static void main(String[] agrs)
	{
		bink b=bink.test();
		bink c=bink.test();
		System.out.println(b==c);
	}
}
 class bink{
//Privatization constructor
	private bink() {
	}
//An object that creates a class internally. This object must also be static
	private static bink a=new bink();
//Provides a public static method that returns the object of the class
	public static bink test()
	{
		return a;
	}
}

Lazy implementation of singleton:

  1. Constructor of privatized class
  2. The object declaring the current class is not initialized
  3. Declare public and static methods that return the current object
public class demo{
	public static void main(String[] agrs)
	{
		bink b=bink.test();
		bink c=bink.test();
		System.out.println(b==c);
	}
}
 class bink{
//Privatization constructor
	private bink() {
	}
//Declare the current class object without initialization. This object must also be declared static
	private static bink a=null;
//Declare public and static methods that return the current class object
	public static bink test()
	{
		if(a==null)
		{
		a=new bink();
		}
		return a;
	}
}

Video notes - Comparison between hungry and lazy:

Hungry Chinese style: disadvantages: the loading time is too long. Advantages: hungry Chinese style is thread safe.

Lazy: advantage: delay the creation of objects. Disadvantages: thread unsafe.

Video notes - order of attribute assignment

Default initialization - display initialization / assignment in code block - initialization in constructor - through attribute Object or property Method

final modifier

1. The class modified by final cannot be inherited and has no subclasses For example, String class, System class and StringBuffer class

 

Compilation error

2. Use final Modified methods can be inherited , But it cannot be overridden by subclasses. For example, the getClass() method in Object

Compilation error

 3. A constant represented by a final variable can only be assigned a value once In fact, variables decorated with fifinal become constants, because the value will not change again.

An error is reported when a is assigned twice

public class Person{
 private final int a;
}

Video notes:

Decorated member variable - non static member variable:

  • Only one chance , You can give this variable a Location of assignment :
    Simultaneous assignment of declarations
    Assignment in anonymous code block
    Assignment in constructor ( All constructors that appear in the class must be written )
public class Person{ 
private static final int a; 
}

Decorated member variable - static member variable:

  • Only one chance , You can give this variable a Location of assignment :
    Simultaneous assignment of declarations
    Assignment in static code block

final modifier local variable:

In particular, when final is used to modify a formal parameter, it appears that this formal parameter is a constant. When we call this method, we assign an argument to the constant formal parameter. Once assigned, this formal parameter can only be used in the method body, but it cannot be re assigned.

final modifier reference variable

public  class student {
String name;
public student()
{
	
}
public void set(String name)
{
	this.name=name;
}
public static void main(String[] args)
{
	final student a1=new student();
a1.set("xx");
a1.set("yy");
}
}

Compile passed

After new again

Compilation error

Interview questions

1. Correct mistakes

public class s{
public int add(final x)
{
return ++x;
}
}

Compilation error, should be changed to

public class s{
public int add(final x)
{
return x+1;
}
}

2.

public class some{
public static void main(String[] args)
{
other o=new other();
new some().add(o);
}
public void add(final other o)
{//o=new other();
o.i++
}
class other{
public int i;
}

After compilation, o is a constant, but i is a variable, so there is no problem

abstract class

Classes defined with the abstract keyword are called abstract classes, and methods defined with this keyword are called abstract methods. An abstract method has no method body, and the method itself has no meaning unless it is overridden. The abstract class carrying the abstract method must be inherited. In fact, the abstract class has no meaning except to be inherited. The syntax for defining abstract classes is as follows:

public abstract class parent{
abstract void test();//Define abstract methods
}
Video notes: 1 While declaring classes , add abstract Modifiers are abstract classes. 2. When declaring the method, add abstract Modifier , And get rid of the big slogan of the method , Add a semicolon at the end , This method is an abstract method.
public  class student {
String name;
public student()
{	
}
public static void main(String[] agrs)
{
st s1=new st(1);//Compilation failed
}
}
abstract class st{
	int age;
	public st(int age)
	{
		this.age=age;
	}
}

Compilation error

When abstract is removed, it is normal

1. Abstract class , out of commission new Keyword to create an object , It is used to let subclasses inherit.
2. Abstract method , Only method declarations , There is no implementation of the method , It is used to make subclasses implement
3. After subclass inherits abstract class , You need to implement abstract methods that are not implemented in the abstract class , Otherwise, this subclass should also be declared as an abstract class
public  abstract class student {
String name;
public abstract void test();
 class st extends student{
	public void test()
	{
		
	}
 }
 

Compile passed

Note: 1 Rewriting the abstract method can meet the requirements of the method with the same name but not the same purpose, which improves the scalability of the program.
           2. Abstract classes must have constructors to be called when subclasses are instantiated.
           3. Abstract methods have only method declarations and no method body
           4. A class containing abstract methods must be an abstract class
           5. Subclasses of abstract classes will be provided in development to instantiate subclass objects and complete relevant operations
           6.abstract cannot be used to modify properties, constructors and other structures, private methods and static methods

Abstract classes are used to model those classes whose parent class cannot determine all the implementations, but whose child classes provide concrete implementation objects.

Code example

public abstract class employee {
private String name;
private int id;
private double salary;
public employee()
{
	super();
}
public employee(String name,int id,double salary)
{
	this.name=name;
	this.id=id;
	this.salary=salary;
}
	public abstract void work();//Abstract method
}
public class manger extends employee {
	private double bonus;
	public manger(double bonus)
	{
		super();
		this.bonus=bonus;
	}
	public manger(String name,int id,double salary,double bonus)
	{
		super(name,id,salary);
		this.bonus=bonus;
	}
	public void work()
	{
		System.out.println("management");
	}

}
public class commonemployee extends employee {
	public void work()
	{
		System.out.println("Employees produce products in front-line workshops");
	}

}
public class employeetest {
public static void main(String[] args)
{
	manger a1=new manger("Xiao Wang",1000,4000,10000);
	a1.work();
	commonemployee b1=new commonemployee();
   b1.work();
}
}

 

Notes on template method design patterns

Scenario: when part of the internal implementation of the function is determined, part of the implementation is uncertain. At this time, you can expose the uncertain part and let the subclass implement it.

That is, to implement an algorithm in software development, the overall steps are very fixed and common. These steps have been written in the parent class. However, some parts are changeable, and the changeable parts can be abstracted for different subclasses to implement. This is a template pattern.

public class timetest {
	public static void main(String[] args)
	{
		st M=new st();
		M.spendtime();
	}
}
abstract class template{
	public void spendtime()
	{//Calculate the time it takes for a piece of code to execute
		long start =System.currentTimeMillis();
		code();//The uncertain part, the changeable part,
		long end =System.currentTimeMillis();
		System.out.println("Time spent is:"+(end-start));
		
	}
	public abstract void code();
}
class st extends template{
	public void code()
	{
		for(int i=2;i<=1000;i++)
		{
			boolean a=true;
			for(int j=2;j<=Math.sqrt(i);j++)
			{
				if(i%j==0)
					a=false;
				break;
			}
			if(a)
			{
				System.out.println(i);
			}
		}
		
	}
}

Common are data access encapsulation, junit unit testing, and so on

Learning is like sailing against the current. If you don't advance, you will fall back. Come on with Xiao Wu

Keywords: Java Back-end JavaSE

Added by 99naa on Sat, 08 Jan 2022 03:13:11 +0200