Java Foundation reviews keywords, singleton design patterns, basic classes, and internal classes

Keywords: Programming Java Attribute Eclipse jvm

Java Basic Review (3)

final keyword

  1. The final-modified content can no longer be changed.
  2. final-modified classes cannot have subclasses, that is, they cannot be inherited
  3. When modifying a member variable, the variable is an end value and cannot be changed any more. It needs to be defined with an initial value.
  4. When modifying a local variable, it is also an end value and cannot be changed any more.
  5. The final modification method is not allowed to be rewritten.

abstract keyword

  1. Abstract methods, abstract classes
  2. Declarations: Functions that do not write function bodies can be called declarations.
  3. In inheritance, when extracting the parent class method, each subclass implements the abstract method, which has a function body. The parent class cannot determine the implementation method in the subclass. Just write a declaration in the parent class. (Responsible for making a rule, content itself to achieve)
  4. Abstract methods: the implementation of methods is given to subclasses. Only methods declared by methods are called abstract methods, and classes with abstract methods are called abstract classes.
  5. Abstract classes do not necessarily have abstract methods, and abstract methods must be abstract classes.
  6. Subclasses that inherit abstract classes must implement Abstract methods, and if not, declare themselves abstract.
  7. Abstract classes cannot be instantiated (objects cannot be created directly), but must be implemented by subclasses, that is, abstract classes must have subclasses.

Compare final, abstract, static, private

Key words that cannot coexist with abstract:

  1. Final: classes modified by final cannot have subclasses, methods cannot be rewritten, classes modified by abstract must have subclasses, and methods must be rewritten.
  2. static: static modified methods can be called directly by class names, abstract must be implemented through subclasses. static modified methods appear with the emergence of bytecode files, earlier than the time of object creation.
  3. private: Modification cannot be rewritten, abstract modification must be rewritten.
  4. There may be no abstract methods in abstract classes, but classes with abstract methods must be abstractly modified, that is, they must be abstract classes.
  5. An abstract method has no method body, but an abstract declaration.

interface:

  1. General interfaces do not write member variables, only write methods - only write rules, and the interface is called method list.
  2. Let the class that implements it implement all the methods in the method list.
  3. Use implements.
  4. How to allocate the functions of parent class and interface: In general, the main functions are placed in the parent class, while the additional functions are placed in the interface, and the interface serves as a complement to the parent class.
  5. Interfaces can not create objects. There can be inheritance relationship between interfaces and interfaces, only multiple inheritance.
  6. Starting with jdk1.7, there may be methods in future interfaces, but methods must be modified with static or default
  7. If a class implements two interfaces, the two interfaces have the same abstract method at the same time. It only needs to rewrite the method once in the class.
    If there is default modifier in the interface, the method does not need to be rewritten.
    If the method names in both interfaces are the same as default methods and the method bodies are different, the method needs to be overridden in the class.
    If the method names and parameters are the same in both interfaces, one interface is an abstract method and the other default modifies the method body. At this point, the class must also override the method.

The difference between interface and abstract classes

1. Abstract classes can be constructed, and interfaces can not be constructed.
2. There may be ordinary member variables in abstract classes and no ordinary member variables in interfaces.
3. The abstract class can contain non-abstract common methods. All methods in the interface must be abstract, and there must be no non-abstract common methods.
4. The access types of abstract methods in abstract classes can be public, protected and (default type, although no error is reported under eclipse, but it should not), but the abstract methods in interfaces can only be public type, and the default is public abstract type.
5. Static methods can be included in abstract classes, but not in interfaces.
6. Both abstract classes and interfaces can contain static member variables. The access type of static member variables in abstract classes can be arbitrary, but the variables defined in interfaces can only be public static final type, and the default is public static final type.
7. A class can implement multiple interfaces, but can only inherit one abstract class.

Design Patterns

  1. The solutions to some common problems summarized by predecessors can be directly used by later generations.
  2. Commonly used design patterns: singletons, factories, agents, adapters, decorations, templates, observers, etc., a total of 23

Singleton Design Patterns

  1. Only one object is allowed, and a singleton class is needed to describe it.

  2. Global access points are implemented by static.

  3. Role: Pass values as global access points

  4. Benefits: It allows two objects to transfer values without any relationship at all, reduces coupling and improves cohesion.

  5. How to achieve low coupling and high cohesion: When dealing with class-to-class relationship, the closer the class-to-class relationship is, the lower the cohesion is. On the contrary, the looser the relationship is, the lower the cohesion is.

  6. In a single case, the only way to provide S is static, and the others are not static.

    Singleton code

    package test;
    
    /*
        Hungry Chinese Style
       Complete the assignment when defining SingleInstance member variables.
     */
    class SingleInstance1{
        //2. Create a static privatized object of the current class inside the singleton class
        //Only hungry Chinese style can add final
        private final static SingleInstance1 s = new SingleInstance1();
       //1. Create constructors and privatize them
        private SingleInstance1()
        {
        }
        //3. Provide singleInstance objects through a common static approach
        public static SingleInstance1 getSingleInstance(){
            return s;
        }
    
        //Functional area
        int num;
    
        public void test()
        {
    
        }
    
    }
    
    /*
        Lazy-man Style
     */
    class SingleInstance2{
    
        //1. Create a construction method for privatization.
        private SingleInstance2(){}
        //2. Create a static privatized object of the current class inside the singleton class
        private static SingleInstance2 s = null;
        //3. Provide singleInstance objects through a common static approach
        public static SingleInstance2 getSingleInstance()
        {
            if(s == null)
            {
                s = new SingleInstance2();
            }
                return s;
        }
    }
    public class demo2 {
        public static void main(String[] args) {
            SingleInstance1 s1 = SingleInstance1.getSingleInstance();
            SingleInstance1 s2 = SingleInstance1.getSingleInstance();
            System.out.println(s1 == s2);//true, which means that the user can only get one unique object
    
            SingleInstance2 s3 = SingleInstance2.getSingleInstance();
            SingleInstance2 s4 = SingleInstance2.getSingleInstance();
            System.out.println(s3 == s4);
    
            //Value transfer:
            //Example: There is a class A and a class B. There is a variable num1 in class A and a variable num2 in class B.
            //Create object a of class A, assign num1=4 to variables, and create object b of class b. The function to achieve is to pass the value of num1 to num2.
            //Direct Value Passing: Not recommended
            A a = new A();
            B b = new B();
    
            //b.num2 = a.num1;
            //Assignment by parameters
            //b.bText(a);
    
            //Pass values by singleton
            a.singleA();
            b.singleB();
        }
    }
    
    class A{
        private int num1 = 4;
        public int getNum1() {
            return num1;}
        public void setNum1(int num1) {
            this.num1 = num1;}
        //For singletons
        public void singleA(){
            SingleInstance1 singleInstance = SingleInstance1.getSingleInstance();
            singleInstance.num = num1;
            System.out.println(num1);
        }
    }
    class B{
        private int num2;
    
        public void bText(A a) {
            num2 = a.getNum1();
        }
        //For singletons
        public void singleB(){
            SingleInstance1 singleInstance = SingleInstance1.getSingleInstance();
            num2 = singleInstance.num;
            System.out.println(num2);
        }
    }
    

Runtime class

  1. Each Java application has a Runtime class instance that enables the application to connect to its running environment.

  2. The current runtime can be obtained through the getRuntime method, and the application cannot create its own instance of the Runtime class.

    Runtime runtime = Runtime.getRuntime();
    		//The default unit is bytes
    		System.out.println(runtime.freeMemory()/1024./1024.);//Free memory
    		System.out.println(runtime.totalMemory()/1024./1024.);//Total memory used by the returned JVM
    		System.out.println(runtime.maxMemory()/1024./1024.);//Maximum amount of memory available
    

polymorphic

  1. Polymorphism: A variety of forms of a thing. Dog = animal = biological flower = plant = biological human = higher animal = animal

  2. Inheritance is the premise of polymorphism

  3. When the parent class and the child class have the same name attribute or method

    • Membership variables: Whether the parent class can be accessed at compilation time and also at runtime
    • Membership method: Can you access the parent class at compile time and see the child class at run time?
    • Static member method: The compilation runs on the parent class
  4. Program running is divided into three stages: pre-compiling, compiling and running.

    • Pre-compiler: When the program opens, the work is done. (Pre-processing command # define)

      • Compilation: From opening the program to clicking on the top left triangle - only the reference type in front can be identified, not the object in the back.

      • Running: Start by clicking on the triangle - the real object is identified, and the object starts to work.

      • Dynamic means: dynamic type, dynamic binding, dynamic loading

      • Dynamic Loading: We can't determine the specific object type at compilation stage, only at runtime can we determine the real working object.

      • Example

        public class Demo9 {
        	public static void main(String[] args) {
        		//Summary: Advantages: It can improve the extensibility of the code, use the functions defined before, and use them directly after, without creating new methods. Example in Demo9
        		Dog dog = new Dog();
        		Cat cat = new Cat();
        		Pig1 pig = new Pig1();
        		Animal animal = new Animal();
        		feedAnimal(dog);
        		feedAnimal(cat);
        		feedAnimal(pig);
        	}
        	
        	//Feed dogs, cats, animals
        	public static void feedAnimal(Animal animal) {//animal = dog = new Dog() polymorphism
        		animal.eat();
        	}
        }
        
        class Animal{
        	public void eat() {
        		System.out.println("Animals eat");
        	}
        }
        
        class Dog extends Animal{
        	@Override
        	public void eat() {
        		System.out.println("Dogs eat bones");
        	}
        }
        
        class Cat extends Animal{
        	@Override
        	public void eat() {
        		System.out.println("Cat eat");
        	}
        }
        
        class Pig1 extends Animal{
        	public void eat() {
        		System.out.println("Pig eating");
        	}
        }
        

Transformation:

  1. Upward transformation: equivalent to automatic type transformation, polymorphism itself is upward transformation.

    Person1 person1 = new Student1();

  2. Downward Transition: Equivalent to Mandatory Type Conversion

  3. Function: Resolves the disadvantage of inability to call subclass-specific attributes in polymorphism

  4. Student1 student121 = new Person1();
    1.Is this a reference to a parent class pointing to an object of a subclass?,Not upward transformation.It is incorrect to use a reference to a parent class.
    2.This is not polymorphism.,So it's not a downward transition.
    

instanceof

  1. This is an operator.

  2. Composition: Object instanceof class or subclass of class

  3. Principle Description: Determine whether the current object is the object of the following class or subclass, and return true, not false

  4. Function: Fault-tolerant processing to increase user experience

  5. There must be inheritance before and after instanceof

  6. Code instance

    public class Demo11 {
    	public static void main(String[] args) {
    		Person2 person2 = new Student2();
    		person2 = new Teacher2();
    		test(person2);
    	}
    	
    	public static void test(Person2 person2) {//person2 = new Teacher2()
    //		// When a reference of type Student2 is used to point to an object of type Teacher2, ClassCastException is reported because Student2 and Teacher2 are not related.
    //		Student2 student2 = (Student2)person2;
    //		student2.run();
    		
    		//fault tolerant
    		//If the object corresponding to person2 is not an object of a subclass of Student2 or Student2, false is returned here.
    		if (person2 instanceof Student2) {
    			Student2 student2 = (Student2)person2;
    			student2.run();
    		}else {
    			System.out.println("Type conversion error");
    		}
    		
    		//There must be inheritance before and after instanceof
    //		Dog1 dog1 = new Dog1();
    //		if (dog1 instanceof Student2) {
    //			
    //		}
    	}
    }
    
    class Person2{
    	String name;
    	int age;
    	
    	public void show() {
    		System.out.println("show");
    	}
    }
    
    class Student2 extends Person2{
    	public void run() {
    		System.out.println("run");
    	}
    }
    
    class Teacher2 extends Person2{
    	public void eat() {
    		System.out.println("eat");
    	}
    }
    
    class Dog1{
    	
    }
    

Object class and three common methods

Is the parent of all classes

Three commonly used methods:

  1. Method of obtaining object information: toString()

    This method is called when printing an object, which changes the object information into a string and returns the object address by default.

    Object attribute information can be output by overwriting the toString() method of the Object class

    class Student
    {
        String name = "Mary";
        int age = 21;
        public String toString()
        {
            return "Full name:"+name+",Age:"+age;
        }
    }
    
  2. Method of judging object equality: equals()

    This method is used to compare whether objects are equal, and this method must be rewritten. The equals() method compares the addresses of two objects, so the method must be rewritten to achieve its purpose.

  3. Object signature: hashCode()

    This method is used to return the physical address (hash code value) of the object in which it belongs. It is often rewritten at the same time as the equals method to ensure that the same two objects have the same. hashCode.

  4. For the description of clone method:
    		 * 1. To complete cloning using clone method, the current class must implement Cloneable interface.
    
    		 * 2. This method must be rewritten if it is to be used.
    
    		 * 3. Not all system classes implement him. For example, Object,Integer,String and so on. His implementations include ArrayList,LinkedList.
    
    		 * 4.clone does not call the new method and the construction method. Clone does not call the construction method. When cloning, the source object is allocated and the source object is allocated first according to the type of the source object.
    
    		 * The same memory, then copy the data from each domain of the source object, and finally return the object address.
    
    		 * When new, the first step is to allocate memory first, then call the constructor to initialize the data, and finally return the object address.
    
    		 * The outside world can manipulate the object through this object address (reference).
    
    		 * 5. Calling clone can not achieve full deep copy. For the object calling clone, it is a deep copy, but for its members, it is still a shallow copy by default.
    
    		 * If you want members to copy deeply, call the member's clone method in the rewritten clone method, and so on.
    
    		 */
    

Internal class

Classes defined within a class, the status of internal classes and member variables of external classes are equal. Internal classes can also be regarded as members of external classes. Members can call each other.

public class Demo14 {
	public static void main(String[] args) {
		Outer outer = new Outer();
		outer.age = 10;
		//How to call members of internal classes
		//two types
		//The first is implemented by means of external classes
		outer.show();
		//Second: Call directly here
    	//References: External classes. Internal classes
    	//Composition: Reference to External Class Objects. Construction Method of new Internal Classes
		Outer.Inner inner = outer.new Inner();
		inner.eat();
	}
}

class Outer{
	int age;
	//Internal class
	class Inner{
		int height;
		public void eat() {
			System.out.println("eat");
		}
	}
	public void show() {
		System.out.println("show");
		Inner inner = new Inner();
		inner.eat();
	}
}

class A1{
	
}

class B1{
	
}
//Explanatory function
//We can indirectly implement multiple inheritance in java through internal classes
class X extends A1{
	class Y extends B1{
		
	}
}

1. Local Internal Classes

  1. Classes defined in a class method

  2. Scope of action: From definition to the end of the current method

  3. When there are both local internal classes and member variables in the method, the use scope of member variables will be expanded from the original basis.

    • Reason: In the current situation, the program will default to final to modify height. So when the method where the local variable is located ends, the variable is not released and the saved value is still there.

    • On the final before the variable:

    • Prerequisite: Variables must coexist with local inner classes. Current local variables are used in local inner classes.

    • To preserve the values of local variables before jdk1.7, add final manually

    • After jdk1.7, the internal mechanism of java has added final by default in front of variables

  4. public class Demo15 {
    	public static void main(String[] args) {
    		Outer1 outer1 = new Outer1();
    		outer1.show();
    		Test11 test11 = new Test11();
    		test11.play();
    	}
    }
    
    class Outer1{
    	int age;
    
    	public void show() {
    		int height=8;
    		//Local inner class
    		class Inner{
    			
    			public void eat() {
    				System.out.println("eat"+height);
    			}
    		}
    		
    		System.out.println("show");
    		Inner inner = new Inner();
    		inner.eat();
    	}
    }
    
    class Test11{
    	public void play() {
    		//We privatize the functions through local internal classes, and collate the code inside the method, which enhances the readability and operability of the code.
    		
    		//Because the definitions of functions cannot be nested, they are implemented through local inner classes.
    //		public void gongneng1(){
    //			System.out.println("Function 1");
    //		}
    //		public void gongneng2(){
    //			System.out.println("Function 2");
    //		}
    		
    		class Inner{
    			public void gongneng1(){
    			    System.out.println("Function 1");
    			}
    			public void gongneng2(){
    				System.out.println("Function 2");
    			}
    		}
    		
    		Inner inner = new Inner();
    		inner.gongneng1();
    		inner.gongneng2();
    	}
    	
    	public void run(){
    		//Because the two methods are part of play's internal class method. Play is not visible outside.
    //		gongneng1();
    //		gongneng2();
    	}
    
    }
    

2. Static internal classes

Static internal classes do not necessarily have static methods, but static internal classes do have static methods.

public class Demo17 {
	public static void main(String[] args) {
		//Out out = new Out();
		//Out.Inn inn = out.new Inn();
		//Creating static internal class objects
		//Composition: new + external class name. Construction method of internal class
		 Out.Inn inn =  new Out.Inn();
		 //Call method
		 inn.play();
		 //Calling static methods
		// inn.show();
		 Out.Inn.show();
	}
}


class Out{
	static int age;
	//Static internal classes do not necessarily have static methods, but static internal classes do have static methods.
	static class Inn{//Static inner class
		public void play() {
			System.out.println("play");
		}
		public static void show() {
			System.out.println("show");
		}
	}
}

3. Anonymous inner classes

Anonymous subclass objects defined in a class method belong to local internal classes.

Notes on Creating Anonymous Internal Class Objects

  1. Anonymous internal class objects must have parent classes or parent interfaces.

The role of anonymous internal class objects:

  1. When only one instance object of the current subclass is used, define it and use it immediately.
  2. When it's hard to name
  3. Better definition of runtime callbacks

The Role of Internal Classes

  1. Indirect realization of multiple inheritance

  2. Convenient Definition

  3. Only external classes can access the properties and methods of the created internal classes (including private methods)

  4. Other classes in the same package are invisible and have good encapsulation.

    public class Demo18 {
    	public static void main(String[] args) {
    		//Research on Anonymous Subclass Objects
    		Animal11 animal = new Animal11();
    		new Animal11().eat();//Anonymous object
    		//Anonymous subclass object
    		//The first is to create anonymous subclass objects using existing subclasses
    		//Use scenarios: Subclasses that have been created can be used multiple times and are suitable for multiple invocations of the same functionality
    		new Dog11().eat();
    		//Second way: Here's also Animal's anonymous subclass object
    		//Direct creation of anonymous subclass objects of Animer without a name
    		//Composition: new + parent's name / interface's name + () + {write the member of the current subclass} +;
    		//Use scenario: Use only once, use will be regarded as garbage collection, applicable to each use can not function.
    		new Animal11() {
    			@Override
    			public void eat() {
    				// TODO Auto-generated method stub
    				super.eat();
    			}
    			public void show() {
    				
    			}
    		}.show();
    		
    		//Anonymous inner class:
    		Test1 test1 = new Test1();
    		test1.canShuTest();
    		test1.canShuTest1();
    	}
    }
    //Research on Anonymous Subclass Objects
    class Animal11 {
    	public void eat() {
    		System.out.println("fu-eat");
    	}
    }
    class Dog11 extends Animal11
    {
    	public void eat() {
    		System.out.println("zi-eat");
    	}
    }
    
    //Anonymous inner class:
    class Test1{
    	public void show() {
    		//Anonymous Inner Class
    		new Animal() {
    			@Override
    			public void eat() {
    				// TODO Auto-generated method stub
    				super.eat();
    			}
    		};
    	}
    	//Ordinary anonymous objects as parameters
    	public void canShuTest() {
    		System.out.println(new Animal());
    	}
    	//Anonymous inner class as parameter
    	public void canShuTest1() {
    		System.out.println(
    			new Animal() {
    				public void eat() {
    					// TODO Auto-generated method stub
    					super.eat();
    				}
    				@Override
    				public String toString() {
    					return "haha";
    				}
    			}
    		);
    	}
    	//Ordinary anonymous objects as return values
    	public Animal fanHuiZhiTest() {
    		return new Animal();
    	}
    	//Anonymous inner class as return value
    	public Animal fanHuiZhiTest1() {
    		return new Animal() {
    			
    		};
    	}
    }
    
    

Posted by ilikephp on Sun, 28 Jul 2019 23:57:09 -0700