Object oriented -- Keyword

Posted by inkel on Fri, 14 Jan 2022 12:59:51 +0100

Keyword: static

sketch:
When we write a class, we are actually describing the properties and behavior of its object without generating a substantive object. Only through the new keyword can we generate an object. At this time, the system will allocate memory space to the object and its methods can be called externally. We sometimes hope that no matter whether objects are generated or how many objects are generated, there is only one copy of some specific data in the memory space. For example, all Chinese have a country name, and each Chinese shares the country name, which does not have to be in each Chinese instance object
A variable representing the name of the country is assigned separately.

  • class Circle{
    private double radius;
    public Circle(double radius){this.radius=radius;}
    public double findArea(){return Math.PIradiusradius;}}
    • Create two Circle objects
      Circle c1=new Circle(2.0); //c1.radius=2.0
      Circle c2=new Circle(3.0); //c2.radius=3.0
  • The variable radius in the Circle class is an instance variable. It belongs to each object of the class and cannot be shared by different objects of the same class.
  • In the above example, the radius of c1 is independent of the radius of c2 and stored in different spaces. The radius change in c1 does not affect the radius of c2, and vice versa
  • If you want all instances of a class to share data, use class variables!
    Design idea of class attribute and class method
  • Class properties are variables shared among objects of this class. When designing a class, analyze which attributes do not change due to different objects, and set these attributes as class attributes. The corresponding method is set to class method.
  • If the method has nothing to do with the caller, such a method is usually declared as a class method. Since the class method can be called without creating an object, the call of the method is simplified.
    Scope of application of static: in Java classes, static can be used to modify attributes, methods, code blocks and internal classes
  • The decorated members have the following characteristics:
     load with class loading
     prior to object existence
     decorated members are shared by all objects
     when the access permission allows, you can directly be called by the class without creating an object
    Code example:
class Circle {
	private double radius;
	public static String name = "This is a circle";
	public static String getName() {
		return name;
	}
	public Circle(double radius) {
		this.radius = radius;
	}
	public double findArea() {
		return Math.PI * radius * radius;
	}
	public void display() {
		System.out.println("name:" + name + "radius:" + radius);
	}
}
public class StaticTest {
	public static void main(String[] args) {
		Circle c1 = new Circle(2.0);
		Circle c2 = new Circle(3.0);
		c1.display();
		c2.display();

Class method

  • When there is no instance of an object, you can use the class name Access the class method modified by static in the form of method name ().
  • Within the static method, you can only access the static modified properties or methods of the class, but not the non static structure of the class.
class Person {
	private int id;
	private static int total = 0;
	public static int getTotalPerson() {
		//id++; // illegal
		return total;}
	public Person() {
		total++;
		id = total;
	}}
public class PersonTest {
	public static void main(String[] args) {
		System.out.println("Number of total is " + Person.getTotalPerson());
		//Static methods can be accessed without creating objects
		Person p1 = new Person();
		System.out.println( "Number of total is "+ Person.getTotalPerson());
}}
  • Because the static method can be accessed without an instance, there cannot be this inside the static method. (super? Yes!)
  • static modified methods cannot be overridden
class Person {
	private int id;
	private static int total = 0;
	public static void setTotalPerson(int total){
		this.total=total; //Illegal. this or super cannot be present in static method
	}
	public Person() {
		total++;
		id = total;
	}}
	public class PersonTest {
		public static void main(String[] args) {
			Person.setTotalPerson(3);
		} }

Singleton design pattern

  • Design pattern is the code structure, programming style and thinking way to solve problems after summarizing and theorizing in a large number of practice. The design of mold eliminates our own thinking and exploration. It's like a classic chess score. We use different chess scores for different chess games. " "Routine"
  • The so-called class singleton design pattern is to take certain methods to ensure that there can only be one object instance for a class in the whole software system, and the class only provides a method to obtain its object instance. If we want a class to generate only one object in a virtual machine, we must first set the access permission of the class constructor to private. In this way, we can't use the new operator to generate the class object outside the class, but we can still generate the class object inside the class. Because you can't get the object of the class from the outside of the class, you can only call a static method of the class to return the object created inside the class. The static method can only access the static member variables in the class. Therefore, the variables pointing to the object of the class generated inside the class must also be defined as static.
    Singleton design pattern - Hungry Chinese style
class Singleton {
// 1. Privatization constructor
	private Singleton() {
	}
	// 2. Provide an instance of the current class internally
	// 4. This instance must also be static
	private static Singleton single = new Singleton();
	// 3. Provide a public static method to return the object of the current class
	public static Singleton getInstance() {
		return single;
	}
}

Singleton design pattern - lazy

class Singleton {
// 1. Privatization constructor
	private Singleton() {
	}
	// 2. Provide an instance of the current class internally
	// 4. This instance must also be static
	private static Singleton single;
	// 3. Provide a public static method to return the object of the current class
	public static Singleton getInstance() {
		if(single == null) {
			single = new Singleton();
		}
	return single;
	}
}
The lazy type still has thread safety problems temporarily. When it comes to multithreading, it can be repaired

Advantages of singleton mode:
Since the singleton mode only generates one instance, the system performance overhead is reduced. When more resources are required for the generation of an object, such as reading the configuration and generating other dependent objects, it can be solved by directly generating a singleton object when the application is started, and then permanently resident in memory.

Singleton design pattern - application scenario
 the counter of the website is generally implemented in single instance mode, otherwise it is difficult to synchronize.
 the log application of the application is generally implemented in the single instance mode, which is generally due to the shared log
The file is always open because there can only be one instance to operate, otherwise the content is not easy to append.
 the design of database connection pool generally adopts single instance mode, because database connection is a database resource.
 in the project, there is generally only one object for the class reading the configuration file. There is no need to generate an object to read every time the configuration file data is used.
 Application is also a typical Application of single example
 Task Manager of Windows is a typical singleton mode
 Recycle Bin of Windows is also a typical single case application. During the operation of the whole system, the Recycle Bin maintains only one instance.

Keyword: final

  • When declaring classes, variables and methods in Java, you can use the keyword final to modify them, indicating "final".
     the class marked final cannot be inherited. Improve the security and readability of the program.
    String class, System class, StringBuffer class
     the method marked final cannot be overridden by subclasses.
    For example: getClass() in Object class.
     variables marked with final (member variables or local variables) are called constants. The name is capitalized and can only be assigned once.
    The member variable of the final tag must be explicitly assigned in the declaration or in each constructor or code block before it can be used.
    final double MY_PI = 3.14;
  1. final modifier class
final class A{
}
class B extends A{ //Error, cannot be inherited.
}
In ancient China, anyone who could not have offspring could be killed final Statement, called "eunuch class"!
  1. final modification method
class A {
	public final void print() {
		System.out.println("A");
	}
}
class B extends A {
	public void print() { // Error, cannot be overridden.
		System.out.println("Ou Peng");
	}
}
  1. final modifier variable - constant
class A {
	private final String INFO = "atguigu"; //declare constant 
	public void print() {
		//The final field A.INFO cannot be assigned
		//INFO = "Ou Peng";
	}
}
The constant name should be capitalized and the content cannot be modified—— Like the edict of an ancient emperor.

static final: global constant
Keyword final application instance:

public final class Test {
	public static int totalNumber = 5;
	public final int ID;
	public Test() {
		ID = ++totalNumber; // The "variable" of the final modifier can be assigned a value in the constructor
	}
	public static void main(String[] args) {
		Test t = new Test();
		System.out.println(t.ID);
		final int I = 10;
		final int J;
		J = 20;
		J = 30; // illegal
	}
}

Abstract classes and abstract methods

With the definition of new subclasses in the inheritance hierarchy, the class becomes more and more specific, while the parent class is more general and general. Class design should ensure that parent and child classes can share features. Sometimes a parent class is designed so abstract that it has no concrete instance. Such a class is called an abstract class.

  • Use the abstract keyword to modify a class, which is called an abstract class.
  • Abstract is used to modify a method, which is called abstract method.
    a. Abstract method: there is only method declaration, no method implementation. End with semicolon:
    For example: public abstract void talk();
    *A class containing abstract methods must be declared as an abstract class.
  • Abstract classes cannot be instantiated. Abstract classes are used to be inherited. Subclasses of abstract classes must override the abstract methods of the parent class and provide method bodies. If you do not override all the abstract methods, it is still an abstract class.
  • abstract cannot be used to modify variables, code blocks and constructors;
  • abstract cannot be used to modify private methods, static methods, final methods, and final classes.
    Abstract class example
abstract class A {
	abstract void m1();
	public void m2() {
		System.out.println("A Class m2 method");
	}
}
class B extends A {
	void m1() {
		System.out.println("B Class m1 method");
	}
}
public class Test {
	public static void main(String args[]) {
		A a = new B();
		a.m1();
		a.m2();
	}
}

Abstract class application

  • Solution
    Java allows class designers to specify that a superclass declares a method but does not provide an implementation, and the implementation of the method is provided by a subclass.
    Such methods are called abstract methods. A class with one or more abstract methods is called an abstract class.
  • Vehicle is an abstract class with two abstract methods
public abstract class Vehicle{
public abstract double calcFuelEfficiency();//Abstract method for calculating fuel efficiency
public abstract double calcTripDistance(); //Abstract method for calculating driving distance
}
public class Truck extends Vehicle{
public double calcFuelEfficiency( ) { //Write a specific method for calculating the fuel efficiency of trucks}
public double calcTripDistance( ) { //Write down the specific method of calculating the distance traveled by the truck}
}
public class RiverBarge extends Vehicle{
public double calcFuelEfficiency( ) { //Write down the specific method for calculating the fuel efficiency of the barge}
public double calcTripDistance( ) { //Write down the specific method for calculating the distance traveled by the barge}
}
Note: abstract classes cannot be instantiated new Vihicle()It's illegal

Inner class

  • When there is an internal part of a thing that needs a complete structure to describe, and the internal complete structure only provides services for external things, the whole internal complete structure is best to make
    Use inner classes.
  • In Java, the definition of one class is allowed to be located inside another class. The former is called the inner class and the latter is called the inner class
    It is called an external class.
  • Inner class is generally used within the class or statement block that defines it. When it is referenced externally, it must be given a complete name.
    The name of the Inner class cannot be the same as the name of the external class containing it;
  • Classification: member inner classes (static member inner classes and non static member inner classes)
    Local inner classes (not to mention modifiers), anonymous inner classes
  • Roles of member inner classes as members of classes:
     unlike external classes, Inner class can also be declared as private or protected;
     the structure of external classes can be called
     Inner class can be declared as static, but non static member variables of outer class cannot be used at this time;
  • The role of a member's inner class as a class
     attribute, method, constructor and other structures can be defined internally
     it can be declared as abstract class, so it can be inherited by other internal classes
     can be declared final
     generate outerclass $innerclass after compilation Class bytecode file (also applicable to local internal classes)
    [note]
  1. Members in non static member inner classes cannot be declared static. Static members can only be declared in external classes or static member inner classes.
  2. The external class accesses the members of the internal class by means of "internal class. Member" or "internal class object. Member"
  3. Member inner classes can directly use all members of outer classes, including private data
  4. When you want to use an inner class in the static member part of an outer class, consider declaring the inner class static

Internal class example

class Outer {
	private int s;
	public class Inner {
		public void mb() {
			s = 100;
			System.out.println("Inside class Inner in s=" + s);
		}
	}
	public void ma() {
		Inner i = new Inner();
		i.mb();
	}
}
public class InnerTest {
	public static void main(String args[]) {
		Outer o = new Outer();
		o.ma();
	}
}
  • How to declare local inner classes
class External class{
method(){
	class Local inner class{
	}
}
{
	class Local inner class{
	}
}
}
  • How to use local inner classes
     it can only be used in the method or code block declaring it, and it is declared before use. Anywhere else
    Cannot use this class
     however, its object can be returned and used through the return value of external method, and the return value type can only be local internal class
    Parent class or parent interface type of
    Characteristics of local inner classes
     the internal class is still an independent class. After compilation, the internal class will be compiled into an independent class Class file, but preceded by the class name and $symbol of the external class, as well as the numerical number.
     it can only be used in the method or code block declaring it, and it is declared before use. You cannot use this class anywhere else.
     local internal classes can use members of external classes, including private ones.
     local internal classes can use local variables of external methods, but they must be final. By local internal classes and bureaus
    Due to different declaration cycles of partial variables.
     the status of local internal classes and local variables is similar, and public,protected, default and private cannot be used
     local internal classes cannot be decorated with static, so they cannot contain static members
    Anonymous Inner Class
  • Anonymous inner classes cannot define any static members, methods and classes. Only one instance of anonymous inner classes can be created. An anonymous inner class must be behind new, which implicitly implements an interface or class.
     format:
    new parent class constructor (argument list) | implementation interface (){
    //The body part of an anonymous inner class
    }
  • Characteristics of anonymous inner classes
     the anonymous inner class must inherit the parent class or implement the interface
     an anonymous inner class can only have one object
     anonymous internal class objects can only be referenced in polymorphic form
interface A{
	public abstract void fun1();
}
public class Outer{
	public static void main(String[] args) {
		new Outer().callInner(new A(){
//The interface cannot be new, but it is special here. The subclass object implements the interface, but the object is not named
			public void fun1() {
				System.out.println("implement for fun1");
	}
		}); // Two steps into one
	}
	public void callInner(A a) {
		a.fun1();
	}
}