JAVA30 days - Basics

Environment variables:

What are the relationships among JDK, JRE and JVM, and what are the main structures of JDK and JRE
JDK = JRE + Java development tools (javac.exe, java.exe, javadoc.exe)
JRD=JVM+JAVA core class library

2. Why configure the path environment variable? How to configure?
JAVA_ Home = directory above bin
path = %JAVA_ HOME%\bin

Define variables

It consists of 26 English letters in case, 0-9_ Or $composition
Package name: all letters are lowercase when composed of multiple words: xxxyyyzzz z
Class name and interface name: when composed of multiple words, the first letter of all words is capitalized: xxyyyzzzz
Variable name and method name: when composed of multiple words, the first word is lowercase, and the first letter of each word is capitalized from the second word: xxxyyzz
Constant name: all letters are capitalized. When there are multiple words, each word is connected with an underscore: xxxw-zzz

Variable classification

integer

  1. byte: -128 ~ 127
  2. Declare a long variable, which must end with 'l' or 'l'
  3. In general, int is used when defining integer variables

floating-point

  1. float: single precision, mantissa can be accurate to 7 significant digits. In many cases, the accuracy is difficult to meet the requirements
  2. Double: double precision, twice the precision of float. This type is usually used
  3. The floating-point constant of Java is double by default. If you declare a floating-point constant, you must add "F" or "F" after it“

Character char

  1. 1 character - 2 bytes
  2. A pair of '' is usually used to define char type variables, and only one character can be written inside
  3. Representation: 1 Declare a character 2 Escape character 3 Use Unicode values directly to represent character constants

Boolean type

Different from other languages: you cannot use 0 to represent false or 1 to represent true

Type conversion

Automatic type promotion

When java performs operations, if the operands are all in the range of int, they all operate in the space of int.

Mandatory type

double d1 =12.9;
int il =(int)d1;// 12 truncation operation

int i2 = 128; 
byte b = (byte)i2;
 System.out.println(b);// -128 accuracy loss 2

exceptional case

String

  1. string can operate with 8 basic data type variables, and the operation can only be connection operation:+
  2. The result of the operation is still of type string

Base system

back=repair-1
 negative:back=The symbol remains unchanged and other bits are reversed,Reverse~:Symbols and other bits change,
Complement operation
 displacement<<Symbol unchanged, 0 filled
 displacement>>The symbol remains unchanged, and the symbol bit is filled

2, Eight, sixteen to ten->Respective level-1
 Ten to two, eight, sixteen->Respective remainder
 Two to eight, sixteen->Fixed digit conversion
 8, Sixteen to two->Fixed digit conversion

Operator (ignored)

array

theory

  1. Understanding of Array: Array is a collection of multiple data of the same type arranged in a certain order, named with a name, and managed uniformly by numbering.
  2. Arrays are ordered
  3. Array is a variable of reference data type.
  4. The element of an array can be either a basic data type or a reference data type
  5. Creating an array object opens up a whole contiguous space in memory
  6. Once the length of the array is determined, it cannot be modified.

One dimensional array

/*        // 1 Initialize array
        // 1.1 Static array
        int[] ai1 = new int[]{10,20,30};
        // 1.2 Dynamic array
        int[] ai2 = new int[3];
        ai2[0] = 10;
        ai2[1] = 20;
        ai2[2] = 30;
//        ai2[3] = 40; // java.lang.ArrayIndexOutOfBoundsException:*/

/*        // 3 Array length
        System.out.println(ai1.length); // 3*/

/*        // 4 Array traversal
        for (int i = 0; i < ai2.length; i++) {
            System.out.println(ai2[i]);
        }
        //10
        //20
        //30*/

       /* // 5 Initialization of array
        *//*Summary:
        Array element is an integer: 0
        Array elements are floating point: 0.0
        Array elements are char type: 0 or '\ ueooe', not 'e' (ascll code 0 corresponds to a space)
        Array elements are boolean: false
        Array element is a reference data type: null
        * *//*

        int[] a1 = new int[3];
        for (int i = 0; i < a1.length; i++) {
            System.out.println(a1[i]);
        }
        //0
        //0
        //0
        System.out.println("*********************************");

        short[] a2 = new short[3];
        for (int i = 0; i < a2.length; i++) {
            System.out.println(a2[i]);
        }
        //0
        //0
        //0
        System.out.println("*********************************");

        float[] a3 = new float[3];
        for (int i = 0; i < a3.length; i++) {
            System.out.println(a3[i]);
        }
        //0.0
        //0.0
        //0.0
        System.out.println("*********************************");

        char[] a4 = new char[3];
        for (int i = 0; i < a4.length; i++) {
            System.out.println(a4[i]);
        }
        // You see n spaces because ascll code 0 corresponds to spaces
        System.out.println("*********************************");

        boolean[] a5 = new boolean[3];
        for (int i = 0; i < a5.length; i++) {
            System.out.println(a5[i]);
        }
        // false
        //false
        //false
        System.out.println("*********************************");

        String[] a6 = new String[3];
        for (int i = 0; i < a6.length; i++) {
            System.out.println(a6[i]);
        }
        //null
        //null
        //null*/


Multidimensional array

        // One dimensional array supplement - type inference
        int[] a1 = new int[]{1,2,3};
        int[] a2 = {1,2,3}; // Type inference

        // 1 two dimensional array initialization
        // 1.1 static initialization
        int[][] aa1 = new int[][]{{1,2,3},{10,20,30}};
        // 1.2 dynamic initialization 1
        int[][] aa2 = new int[3][3];
        // 1.3 dynamic initialization 2
        int[][] aa3 = new int[3][];


/*        // 2 call
        System.out.println(aa2[0][1]); // 0
//        System.out.println(aa3[0][1]); // NullPointerException*/

/*        // 3 assignment
        aa3[0] = new int[]{1,24,5};
        System.out.println(aa3[0][1]); // 24*/

/*        // 4 ergodic
        for (int i = 0; i < aa1.length; i++) {
            for (int j = 0; j < aa1[i].length; j++) {
                System.out.println(aa1[i][j]);
            }
        }
        // 1
        //2
        //3
        //10
        //20
        //30*/
/*

        // 5 Array initialization, address value - pay attention to whether it is one-dimensional or two-dimensional and type
        System.out.println(a1); // [I@1b6d3586
        System.out.println(aa2); // [[I@4554617c
        System.out.println(aa2[0]); // [I@74a14482
        System.out.println(aa2[0][0]); // 0
        System.out.println(aa3[0]); // null
*/

Object oriented (I)

Object to create class = instantiation of class = instantiation of class
Call the structure of an object through object. Property or object. Method

Memory parsing

Attribute (member variable) vs local variable

We must explicitly assign values before calling local variables.
Class is address passing, shallow copy

/*
 * Use of properties in class
 * 
 * Attribute (member variable) vs local variable
 * 1.Similarities:
 * 		1.1  Define the format of variable: data type variable name = variable value
 * 		1.2 Declaration before use
 * 		1.3 Variables have their corresponding scopes 
 * 
 * 
 * 2.difference:
 * 		2.1 Different positions declared in the class
 * 		Attribute: directly defined in a pair of {} of the class
 * 		Local variables: variables declared within methods, method parameters, code blocks, constructor parameters, and constructors
 * 		
 * 		2.2 Differences about permission modifiers
 * 		Attribute: when declaring an attribute, you can specify its permission and use the permission modifier.
 * 			Common permission modifiers: private, public, default, protected -- > encapsulation
 * 			At present, when you declare properties, you can use the default.
 * 		Local variables: permission modifiers are not allowed.
 * 
 * 		2.3 Default initialization value:
 * 		Attribute: the attribute of a class has a default initialization value according to its type.
 * 			Integer (byte, short, int, long): 0
 * 			Floating point (float, double): 0.0
 * 			Character type (char): 0 (or '\ u0000')
 * 			boolean: false
 * 
 * 			Reference data type (class, array, interface): null
 * 
 * 		Local variable: no default initialization value.
 *  		This means that we must explicitly assign values before calling local variables.
 * 			In particular: when the formal parameter is called, we can assign a value.
 * 
 * 		2.4 Location loaded in memory:
 * 		Properties: load into heap space (non static)
 * 		Local variables: loading into stack space
 * 
 */

JVM

VM Stack ,This is the stack structure mentioned at ordinary times. We store local variables in the stack structure
 Pile, we will new Out of the structure(such as:Array, object)Loaded in pair space. supplement:Object properties(wrong static of) Loaded in heap space.
Method area:Class loading information, constant pool, static field

Anonymous object

new xx has no value assigned. It is generally used as a method parameter for this object

On method overloading

In the same class, more than one method with the same name is allowed, as long as their parameter number or parameter type are different.
It has nothing to do with the permission modifier, return value type, formal parameter variable name and method body of the method!

Method of variable number formal parameters

/*
 * 1.jdk 5.0 New content
 * 2.Specific use:
 *   2.1 Variable number parameter format: data type Variable name
 *   2.2 When calling the method of variable number formal parameters, the number of parameters passed in can be: 0, 1, 2,...
 *   2.3 Methods with variable number formal parameters have the same name as those in this class, and methods with different formal parameters constitute overloads
 *   2.4 Arrays with the same method name and parameter type as those in this class do not constitute overloads. In other words, the two cannot coexist.
 *   2.5 The variable number parameter is in the parameter of the method and must be declared at the end
 * 	 2.6  A variable number parameter can declare at most one deformable parameter in a method parameter.
 * 
 */

pass by value

assignment

 * 
 *  If the variable is a basic data type, the data value saved by the variable is assigned at this time.
 *  If the variable is a reference data type, the assigned value is the address value of the data saved by the variable.

Transmission parameter

 * If the parameter is a basic data type, what the argument assigns to the formal parameter is the data value actually stored by the argument.
 * If the parameter is a reference data type, the address value of the stored data of the parameter is assigned to the formal parameter.


recursion

 * Use of recursive methods (understand)
 * 1.Recursive method: a method body calls itself.
 * 2. Method recursion contains an implicit loop that repeats a piece of code, but this repetition does not need loop control.
 * Recursion must recurse in the known direction, otherwise this recursion will become infinite recursion, similar to an endless loop.

Encapsulation and hiding


 * Object oriented feature 1: encapsulation and hiding
 * 1, Introduction of problems:
 *  When we create a class object, we can"object.attribute"Assign values to the properties of the object. Here, the assignment operation is subject to
 *  Attribute data type and storage range. In addition, there are no other constraints. However, in practical problems, we often need to assign values to attributes
 *  Add additional restrictions. This condition cannot be reflected in the attribute declaration. We can only add constraints through methods. (for example: setLegs())
 *  At the same time, we need to avoid users from using it again"object.attribute"Assign a value to an attribute in the same way. You need to declare the property private(private).
 *  -->At this point, the encapsulation is reflected for attributes.
 * 
 * 2, Embodiment of encapsulation:
 * We will the properties of the class xxx Privatization(private),At the same time, provide public(public)Method to get(getXxx)And settings(setXxx)The value of this property
 * 
 *  Expansion: embodiment of encapsulation:① Above  ② Private method without external exposure  ③ Singleton mode   ...
 *  
 * 
 * 3, The embodiment of encapsulation requires permission modifiers.
 * 1.Java Specified 4 kinds of permissions (from small to large): private,Default protected ,public 
 * 2.4 Three kinds of permissions can be used to modify classes and their internal structures: properties, methods, constructors, and internal classes
 * 3.Specifically, all four permissions can be used to modify the internal structure of a class: attributes, methods, constructors, and internal classes
 *        If you want to modify a class, you can only use: default public

constructor

Property assignment order

/*
 * Summary: sequence of attribute assignment
 * 
 * 
 * ① Default initialization
 * ② Explicit initialization
 * ③ Initialization in constructor
 * 
 * ④ Assign values by means of "object. Method" or "object. Attribute"
 * 
 * Sequence of the above operations: ① - ② - ③ - ④  
 * 
 */

this

/*
 * this Use of keywords:
 * 1.this It can be used to modify and call: properties, methods and constructors
 * 
 * 2.this Modification properties and methods:
 *   this Understood as: the current object or the object currently being created
 * 
 *  2.1  In the method of class, we can call the current object property or method by using "this. Property" or "this. Method". But,
 *   Usually, we choose to omit "this.". In special cases, if the formal parameter of a method has the same name as the attribute of a class, we must explicitly
 *   The use of "this. Variable" indicates that this variable is an attribute, not a formal parameter.
 * 
 *  2.2 In the constructor of the class, we can call the object property or method currently being created by using "this. Property" or "this. Method".
 *  However, usually, we choose to omit "this.". In special cases, if the formal parameter of the constructor has the same name as the attribute of the class, we must explicitly
 *   The use of "this. Variable" indicates that this variable is an attribute, not a formal parameter.
 * 
 * 3. this Invoking Constructors 
 * 	  ① In the class constructor, we can explicitly use the "this (formal parameter list)" method to call other constructors specified in this class
 *    ② Constructor cannot call itself through "this (formal parameter list)"
 *    ③ If there are n constructors in a class, "this (formal parameter list)" is used in up to n - 1 constructors
 *    ④ Specifies that "this (formal parameter list)" must be declared on the first line of the current constructor
 *    ⑤ Inside the constructor, at most one "this (formal parameter list)" can be declared to call other constructors
 * 
 * 
 */

package and important

package

In order to better realize the management of classes in the project, the concept of package is provided
 use package Declare the package to which the class or interface belongs, which is declared on the first line of the source file
 Interfaces and classes with the same name cannot be named under the same package.
Under different packages, you can name interfaces and classes with the same name.

important

 * import:Import
 * 1. Explicit use in source files import Structure imports the classes and interfaces under the specified package
 * 2. The declaration is between the declaration of the package and the declaration of the class
 * 3. If you need to import multiple structures, write them out side by side
 * 4. have access to"xxx.*"Means that it can be imported xxx All structures under the package
 * 5. If the class or interface used is java.lang If it is defined under the package, it can be omitted import structure
 * 6. If the class or interface used is defined in this package, it can be omitted import structure
 * 7. If classes with the same name under different packages are used in the source file, at least one class must be displayed in the form of full class name.
 * 8. use"xxx.*"Mode indicates that it can be called xxx All structures under the package. But if you use xxx The structure under the sub package still needs to be explicitly imported
 * 
 * 9. import static:Imports a static structure from the specified class or interface:Property or method. 

Object oriented (medium)

Inheritance

DEBUG

rewrite

/*
 * Override of method (override / overwrite)
 * 
 * 1.Override: after a subclass inherits the parent class, it can override the methods with the same name and parameters in the parent class
 * 
 * 2.Application: after rewriting, when a subclass object is created and a method with the same name and parameter in the child parent class is called through the subclass object, the actual execution is the subclass rewriting the parent class method.
 * 
 * 3. Provisions for rewriting:
 * 			Method declaration: permission modifier return value type method name (formal parameter list) throw exception type{
 * 						//Method body
 * 					}
 * 			The Convention is commonly known as: the method in the subclass is called the overridden method, and the method in the parent class is called the overridden method
 * 		① The method name and parameter list of the method overridden by the subclass are the same as those of the method overridden by the parent class
 *      ② The permission modifier of the method overridden by the subclass is not less than the permission modifier of the method overridden by the parent class
 *      	>Special case: a subclass cannot override a method declared as private permission in the parent class
 *      ③ Return value type:
 *      	>If the return value type of the method overridden by the parent class is void, the return value type of the method overridden by the child class can only be void
 *      	>If the return value type of the method overridden by the parent class is type A, the return value type of the method overridden by the child class can be class A or a subclass of class A
 *      	>If the return value type of the method overridden by the parent class is the basic data type (for example, double), the return value type of the method overridden by the child class must be the same basic data type (it must also be double)
 *		④ The exception type thrown by the method overridden by the subclass shall not be greater than the exception type thrown by the method overridden by the parent class (specifically in exception handling)
 *	**********************************************************************
 *		Methods with the same name and parameters in the subclass and parent class are either declared non static (consider overriding), or both declared static (not overriding).	
 *
 * Interview question: overloading and rewriting of distinguishing methods
 */

Permission modifier

//Ordinary classes (non subclasses) under different packages need to use the Order class. You cannot call properties and methods declared as private, default and protected permissions
//In subclasses of different packages, properties and methods declared as private and default permissions in the Order class cannot be called

super

/*
 * super Use of keywords
 * 1.super Understood as: parent class
 * 2.super Can be used to call: properties, methods, constructors
 * 
 * 3.super Use of: calling properties and methods
 * 
 *   3.1 We can in subclass methods or constructors. Call explicitly by using "super. Attribute" or "super. Method"
 *   A property or method declared in a parent class. However, in general, we are used to omitting "super."
 *   3.2 Special case: when the properties of the same name are defined in the child class and the parent class, we must explicitly call the properties declared in the parent class in the subclass.
 *   Using "super. Attribute" means that the attribute declared in the parent class is called.
 *   3.3 Special case: when a child rewrites the method in the parent class, we want to call the method that is rewritten in the parent class in the subclass method.
 *   Using "super. Method" means that the method overridden in the parent class is called.
 * 
 * 4.super Invoking Constructors 
 * 	 4.1  We can explicitly use "super (formal parameter list)" in the constructor of the subclass to call the specified constructor declared in the parent class
 *   4.2 "super(The use of formal parameter list must be declared in the first line of subclass constructor!
 *   4.3 In the class constructor, we can only choose one of "this" or "super" and cannot appear at the same time
 *   4.4 In the first line of the constructor, if there is no explicit declaration of "this (formal parameter list)" or "super (formal parameter list)", the constructor of the null parameter of the parent class is called by default: super()
 *   4.5 Among multiple constructors of a class, at least one class uses "super (formal parameter list)" in the constructor to call the constructor in the parent class
 */

polymorphic

/*
 * Object oriented feature 3: polymorphism
 * 
 * 1.Understanding polymorphism: it can be understood as multiple forms of a thing.
 * 2.What is polymorphism
 *   Object polymorphism: the reference of the parent class points to the object of the child class (or the reference assigned to the parent class by the object of the child class)
 *   
 * 3. Use of polymorphism: virtual method calls
 *   With object polymorphism, we can only call the methods declared in the parent class at compile time, but at run time, we actually execute the methods of the child class overriding the parent class.
 *   Summary: compile and look at the left; Run, look to the right.
 *   
 * 4.The premise of using polymorphism: ① the inheritance relationship of classes ② the rewriting of methods
 * 
 * 5.The polymorphism of objects is only applicable to methods, not attributes (see the left for compilation and operation)
 */
		System.out.println("*******************");
		//Object polymorphism: the reference of the parent class points to the object of the child class
		Person p2 = new Man();
//		Person p3 = new Woman();
		//Use of polymorphism: when calling a method with the same name and parameters as the child parent class, the actual implementation is the virtual method call, which is the method of the child class overriding the parent class
		p2.eat();
		p2.walk();
		
//		p2.earnMoney();

Polymorphic examples

//Example 1 of polymorphism:
public class AnimalTest {
	
	public static void main(String[] args) {
		
		AnimalTest test = new AnimalTest();
		test.func(new Dog());
		
		
		test.func(new Cat());
	}
	
	public void func(Animal animal){//Animal animal = new Dog();
		animal.eat();
		animal.shout();
		
		if(animal instanceof Dog){
			Dog d = (Dog)animal;
			d.watchDoor();
		}
	}
	
//	public void func(Dog dog){
//		dog.eat();
//		dog.shout();
//	}
//	public void func(Cat cat){
//		cat.eat();
//		cat.shout();
//	}
}


class Animal{
	
	
	public void eat(){
		System.out.println("Animals: eating");
	}
	
	public void shout(){
		System.out.println("Animal: call");
	}
	
	
}

class Dog extends Animal{
	public void eat(){
		System.out.println("Dogs eat bones");
	}
	
	public void shout(){
		System.out.println("Woof! Woof! Woof!");
	}
	
	public void watchDoor(){
		System.out.println("Janitor");
	}
}
class Cat extends Animal{
	public void eat(){
		System.out.println("Cats eat fish");
	}
	
	public void shout(){
		System.out.println("Meow! Meow! Meow!");
	}
}

Virtual method

Use of downward transformation

Polymorphism is left-handed
Turn down yes, it must be higher than the right and lower than the left?

		//Cannot call methods and properties unique to subclasses: p2 is of type Person at compile time.
		p2.name = "Tom";
//		p2.earnMoney();
//		p2.isSmoking = true;
		//With the polymorphism of objects, the properties and methods specific to subclasses are actually loaded in memory, but because variables are declared as parent types, the
		//At compile time, only properties and methods declared in the parent class can be called. Subclass specific properties and methods cannot be called.
		
		//How can I call subclass specific properties and methods?
		//Transition down: use a cast type converter.
		Man m1 = (Man)p2;
		m1.earnMoney();
		m1.isSmoking = true;

Use of instanceof keyword

When materializing, instanceof returns tru on both sides of the equation, which is at least higher than that on the right?
Only parent and child classes return true

		//When using strong conversion, an exception of ClassCastException may occur.
//		Woman w1 = (Woman)p2;
//		w1.goShopping();
		
		/*
		 * instanceof Use of keywords
		 * 
		 * a instanceof A:Judge whether object a is an instance of class A. If yes, return true; If not, false is returned.
		 * 
		 * 
		 *  Usage scenario: in order to avoid the exception of ClassCastException during downward transformation, we first
		 *  Judge the instanceof. Once true is returned, perform the downward transformation. If false is returned, no downward transformation is performed.
		 *  
		 *  If a instanceof A returns true, a instanceof B also returns true
		 *  Where class B is the parent of class A.
		 */
		if(p2 instanceof Woman){
			Woman w1 = (Woman)p2;
			w1.goShopping();
			System.out.println("******Woman******");
		}
		
		if(p2 instanceof Man){
			Man m2 = (Man)p2;
			m2.earnMoney();
			System.out.println("******Man******");
		}
		
		if(p2 instanceof Person){
			System.out.println("******Person******");
		}
		if(p2 instanceof Object){
			System.out.println("******Object******");
		}

Properties of polymorphic call subclasses

The polymorphism of objects is only applicable to methods, not attributes (see the left for compilation and operation)
After polymorphism, you can call subclass properties by calling subclass methods of the same kind

class Base {
	int count = 10;

	public void display() {
		System.out.println(this.count);
	}
}

class Sub extends Base {
	int count = 20;

	public void display() {
		System.out.println(this.count);
	}
}

public class FieldMethodTest {
	public static void main(String[] args) {
		Sub s = new Sub();
		System.out.println(s.count);//20
		s.display();//20
		
		Base b = s;//Polymorphism
		//==: for reference data types, the comparison is whether the address values of two reference data type variables are the same
		System.out.println(b == s);//true
		System.out.println(b.count);//10
		b.display();//20
	}
}

Use of Object class

 * java.lang.Object class
 * 1.Object Class is all Java Root parent of class
 * 2.If not used in the declaration of the class extends Keyword indicates its parent class, then the default parent class is java.lang.Object class 
 * 3.Object Functions in class(Properties and methods)It is universal.
 * 	Properties: None
 *  method: equals() / toString() / getClass() /hashCode() / clone() / finalize()
 *     wait() , notify(),notifyAll()
 * 
 * 4. Object Class only declares a constructor with an empty parameter

equals and==

/*
 * 
 * Interview question: = = what's the difference between equals
 * 
 * 1, Review the use of = =:
 * == : operator
 * 1. Can be used in basic data type variables and reference data type variables
 * 2. If you are comparing basic data type variables: compare whether the data saved by the two variables are equal. (not necessarily the same type)
 *    If the comparison is a reference data type variable: compare whether the address values of the two objects are the same That is, whether two references point to the same object entity
 * Supplement: when the = = symbol is used, the basic variable types on the left and right sides of the symbol must be consistent. (for example, int==double returns true, but int==boolean compilation error)
 * 
 * 2, Use of equals() method:
 * 1. Is a method, not an operator
 * 2. Applies only to reference data types
 * 3. Object Definition of equals() in class:
 *    public boolean equals(Object obj) {
	        return (this == obj);
	  }
 *    Note: equals() and = = defined in the Object class have the same function: compare whether the address values of the two objects are the same That is, whether two references point to the same Object entity
 * 
 * 4. String, Date, File, wrapper class, etc. override the equals() method in the Object class. After rewriting, the comparison is not
 *    Whether the addresses of the two references are the same, but whether the "entity content" of the two objects is the same.
 *    
 * 5. In general, if we use equals() in our custom class, we usually compare whether the "entity content" of the two objects is the same. So, we
 *    You need to override equals() in the Object class
 *    Rewriting principle: compare whether the entity contents of two objects are the same
 */

toString

   1. When we output a reference to an object, we actually call the current object toString()
 * 
 * 2. Object In class toString()Definition of:
 *   public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
     }
 * 
 * 3. image String,Date,File,The wrapper class has been rewritten Object Class toString()method.
 *    So that when the object is called toString()When, return"Entity content"information
 *    
 * 4. Custom classes can also be overridden toString()Method, when called, returns the name of the object"Entity content"

JUnit unit test

 * 2.establish Java Class for unit testing.
 *   At this time Java Class requirements:① Such is public of  ②This class provides a public parameterless constructor
 * 3.Unit test methods are declared in this class.
 *   The unit test method at this time: the permission of the method is public,No return value, no formal parameter
 * 
 * 4.The unit test method needs to declare the following comments:@Test,And import in the unit test class: import org.junit.Test;

Use of packaging

Basic data type<--->Packaging: JDK 5.0 New features: automatic packing and automatic unpacking
 Basic data type and packing class--->String:call String Overloaded valueOf(Xxx xxx)
String--->Basic data type and packing class:Calling the wrapper class parseXxx(String s)
     Note: during conversion, an error may occur NumberFormatException

Object oriented (Part 2)

static

/*
 * static Use of keywords
 * 
 * 1.static:Static
 * 2.static Can be used to modify: attributes, methods, code blocks, internal classes
 * 
 * 3.Use static to modify attributes: static variables (or class variables)
 * 		3.1 Attributes are divided into static attributes vs non static attributes (instance variables) according to whether static modification is used
 * 		   Instance variable: we have created multiple objects of the class, and each object independently has a set of non static properties in the class. When modifying one of the objects
 *              Non static attributes do not result in the modification of the same attribute value in other objects.
 *       Static variable: we create multiple objects of the class, and multiple objects share the same static variable. When a static variable is modified through an object, it will cause
 *              When other objects call this static variable, it is modified.
 * 		3.2 static Additional description of modified attributes:
 * 			① Static variables are loaded as the class is loaded. It can be called by "class. Static variable"
 *          ② Static variables are loaded before objects are created.
 *          ③ Since the class will only be loaded once, only one copy of the static variable will exist in memory: in the static field of the method area.
 *          
 *          ④		Class variable 	 Instance variable
 *          class 		 yes 		 no
 *          object 		 yes 		 yes
 *          
 *      3.3 Example of static attribute: system out;  Math. PI;
 * 
 * 4.Using static to decorate methods: static methods
 * 		① It is loaded as the class is loaded, and can be called through "class. Static method"
 * 		②			Static method 	 Non static method
 *          class 		 yes 		 no
 *          object 		 yes 		 yes
 * 		③ In static methods, only static methods or properties can be called
 *        In non static methods, you can call either non static methods or properties or static methods or properties
 * 
 * 5. static Note:
 *    5.1 this keyword and super keyword cannot be used in static methods
 *    5.2 By default, it can not be written. If it is written, it is the class name xx
 *    
 * 6. During development, how to determine whether an attribute should be declared as static?
 * 		> Attributes can be shared by multiple objects and will not vary with different objects.
 * 		> Constants in classes are also often declared as static
 * 
 *    During development, how to determine whether a method should be declared as static?
 *    	> The method for operating static properties is usually set to static
 *      > Methods in tool classes are traditionally declared as static. For example: Math, Arrays, Collections
 */

Design pattern - single example

Hungry Han style

public class SingletonTest1 {
	public static void main(String[] args) {
//		Bank bank1 = new Bank();
//		Bank bank2 = new Bank();
		
		Bank bank1 = Bank.getInstance();
		Bank bank2 = Bank.getInstance();
		
		System.out.println(bank1 == bank2); // true
	}
}


class Bank{
	
	//1. Constructor of privatization class
	private Bank(){
		
	}
	
	//2. Create class objects internally
	//4. This object must also be declared static
	private static Bank instance = new Bank(); //Hungry Han style
	
	//3. Provide public static methods to return class objects
	public static Bank getInstance(){
		return instance;
	}
}

Lazy style

public class SingletonTest2 {
	public static void main(String[] args) {
		
		Order order1 = Order.getInstance();
		Order order2 = Order.getInstance();
		
		System.out.println(order1 == order2);
		
	}
}


class Order{
	
	//1. Constructor of privatization class
	private Order(){
		
	}
	
	//2. Declare the current class object without initialization
	//4. This object must also be declared as static
	private static Order instance = null; // Lazy style
	
	//3. Declare public and static methods that return the current class object
	public static Order getInstance(){
		
		if(instance == null){
			
			instance = new Order();
			
		}
		return instance;
	}
	
}

The difference between hungry and lazy

 * 3. Distinguish between hungry and lazy
 *   Hungry Han style:	
 *   	Disadvantage: the object takes too long to load.
 *   	Benefit: hungry Chinese style is thread safe
 *   
 *   Lazy: benefit: delay the creation of objects.
 * 		  The disadvantage of the current writing method: thread is not safe.--->When the multithreaded content is, modify it again

Advantages of singleton mode:

Since the singleton pattern generates only one instance, the system performance overhead is reduced when an object
When generating more resources, such as reading configuration and generating other dependent objects, you can
To generate a singleton object directly when the application starts, and then permanently reside in memory
To solve the problem.

main

 * main()Instructions for using the method:
 * 1. main()Method as an entry to the program
 * 2. main()Method is also a common static method(Static can only call static methods or properties)
 * 3. main()Method can be used as a way for us to interact with the console. (before: use) Scanner)

Code block

/*
 * Class: code block (or initialization block)
 * 
 * 1. Function of code block: used to initialize classes and objects
 * 2. If the code block is decorated, you can only use static
 * 3. Classification: static code block vs 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 can only call static attributes and static methods, not non static structures
 * 
 * 5. 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
 * 		>Static attributes, static methods, or non static attributes and non static methods can be called in non static code blocks
 * 
 */

By parent and child, static first, static code block > normal code block > constructor

package com.atguigu.java3;
//Summary: by parent and child, static first
class Root{
	static{
		System.out.println("Root Static initialization block for");
	}
	{
		System.out.println("Root Normal initialization block");
	}
	public Root(){
		super();
		System.out.println("Root Parameterless constructor for");
	}
}
class Mid extends Root{
	static{
		System.out.println("Mid Static initialization block for");
	}
	{
		System.out.println("Mid Normal initialization block");
	}
	public Mid(){
		super();
		System.out.println("Mid Parameterless constructor for");
	}
	public Mid(String msg){
		//Call overloaded constructors in the same class through this
		this();
		System.out.println("Mid A constructor with parameters, whose parameter values are:"
			+ msg);
	}
}
class Leaf extends Mid{
	static{
		System.out.println("Leaf Static initialization block for");
	}
	{
		System.out.println("Leaf Normal initialization block");
	}	
	public Leaf(){
		//Call the constructor with a string parameter in the parent class through super
		super("Shang Silicon Valley");
		System.out.println("Leaf Constructor for");
	}
}
public class LeafTest{
	public static void main(String[] args){
		new Leaf(); 
		System.out.println();
		new Leaf();
	}
}


final

/*
 * final:Final
 * 
 * 1. final Structures that can be modified: classes, methods, variables
 * 
 * 2. final Used to decorate a class: this class cannot be inherited by other classes.
 *          For example: String class, System class, StringBuffer class
 * 
 * 3. final Used to modify a method: indicates that this method cannot be overridden
 * 			For example: getClass() in Object class;
 * 
 * 4. final Used to modify variables: at this time, the "variable" is called a constant
 * 	    4.1 final Decorated attribute: the positions where assignment can be considered are: explicit initialization, initialization in code block and initialization in constructor
 * 		4.2 final Modify local variables:
 *           Especially when final is used to modify a formal parameter, it indicates that the formal parameter is a constant. When we call this method, we assign an argument to the constant formal parameter. Once assigned
 *           Later, this parameter can only be used in the method body, but it cannot be re assigned.
 *           
 *  static final Used to modify attributes: global constants
 */

Attribute complex assignment order

Abstract classes and abstract methods

/*
 * abstract Use of keywords
 * 1.abstract:Abstract
 * 2.abstract Structures that can be modified: classes, methods
 * 
 * 3. abstract Decoration class: abstract class
 * 		> This class cannot be instantiated
 *      > There must be a constructor in the abstract class to be called when subclass instantiation (involving the whole process of subclass object instantiation)
 *      > During development, subclasses of abstract classes will be provided to instantiate subclass objects and complete relevant operations
 * 
 * 
 * 4. abstract Modification method: abstract method
 * 		> Abstract methods have only method declarations and no method bodies
 * 		> A class containing abstract methods must be an abstract class. Conversely, there can be no abstract methods in an abstract class.
 *      > A subclass can be instantiated only after it overrides all the abstract methods in the parent class
 *        If the subclass does not override all the abstract methods in the parent class, the subclass is also an abstract class and needs to be modified with abstract
 * 
 * abstract Notes on use:
 * 1.abstract Cannot be used to decorate: properties, constructors, etc
 * 
 * 2.abstract Cannot be used to modify private methods, static methods, final methods, and final classes
 * 
 */

Abstract - anonymous objects and anonymous subclass objects that create abstract classes

/*
 * Anonymous subclass of abstract class
 * Person Is an abstract class
 * 
 */
public class PersonTest {
	
	public static void main(String[] args) {
		
		
		
		Worker worker = new Worker();
		method1(worker);//Non anonymous class non anonymous object
		
		method(new Student());//Anonymous object
		
		method1(new Worker());//Non anonymous class object
		
		System.out.println("********************");
		
		//Created an object with an anonymous subclass: p
		Person p = new Person(){

			@Override
			public void eat() {
				System.out.println("Eat something");
			}

			@Override
			public void breath() {
				System.out.println("Breathe");
			}
			
		};
		
		method1(p);
		System.out.println("********************");
		//Create anonymous objects of anonymous subclasses
		method1(new Person(){
			@Override
			public void eat() {
				System.out.println("Eat delicious food");
			}

			@Override
			public void breath() {
				System.out.println("Take a good breath of fresh air");
			}
		});
	}
	
	
	public static void method1(Person p){
		p.eat();
		p.breath();
	}
	
	public static void method(Student s){
		
	}
}

class Worker extends Person{

	@Override
	public void eat() {
	}

	@Override
	public void breath() {
	}
	
}

Template method design pattern

/*
 * Application of abstract classes: design patterns of template methods
 * 
 */
public class TemplateTest {
	public static void main(String[] args) {
		
		SubTemplate t = new SubTemplate();
		
		t.spendTime();
	}
}

abstract class Template{
	
	//Calculate the time it takes for a piece of code to execute
	public void spendTime(){
		
		long start = System.currentTimeMillis();
		
		this.code();//Uncertain part, changeable part
		
		long end = System.currentTimeMillis();
		
		System.out.println("The time spent is:" + (end - start));
		
	}
	
	public abstract void code();
	
	
}

class SubTemplate extends Template{

	@Override
	public void code() {
		
		for(int i = 2;i <= 1000;i++){
			boolean isFlag = true;
			for(int j = 2;j <= Math.sqrt(i);j++){
				
				if(i % j == 0){
					isFlag = false;
					break;
				}
			}
			if(isFlag){
				System.out.println(i);
			}
		}

	}
	
}

Interface

definition

 * 5. Java In development, interfaces are implemented by letting classes(implements)To use.
 *    If the implementation class covers all abstract methods in the interface, the implementation class can be instantiated
 *    If the implementation class does not cover all the abstract methods in the interface, the implementation class is still an abstract class
 *    
 * 6. Java Class can implement multiple interfaces   --->Made up Java Limitations of single inheritance
 *   Format: class AA extends BB implements CC,DD,EE
 *   
 * 7. Interfaces can inherit from one interface to another, and multiple interfaces can inherit
 * 
 * *******************************
 * 8. The specific use of the interface reflects polymorphism
 * 9. Interface can actually be regarded as a specification

Use of interfaces

/*
 * Use of interfaces
 * 1.The interface also meets polymorphism
 * 2.Interface actually defines a specification
 * 3.Experience interface oriented programming in development!
 * 
 */
public class USBTest {
	public static void main(String[] args) {
		
		Computer com = new Computer();
		//1. Create a non anonymous object of the non anonymous implementation class of the interface
		Flash flash = new Flash();
		com.transferData(flash);
		
		//2. Create the anonymous object of the non anonymous implementation class of the interface
		com.transferData(new Printer());
		
		//3. Create a non anonymous object of the anonymous implementation class of the interface
		USB phone = new USB(){

			@Override
			public void start() {
				System.out.println("The phone starts working");
			}

			@Override
			public void stop() {
				System.out.println("End of mobile phone work");
			}
			
		};
		com.transferData(phone);
		
		
		//4. Create the anonymous object of the anonymous implementation class of the interface
		
		com.transferData(new USB(){
			@Override
			public void start() {
				System.out.println("mp3 start-up");
			}

			@Override
			public void stop() {
				System.out.println("mp3 power cut-off");
			}
		});
	}
}

class Computer{
	
	public void transferData(USB usb){//USB usb = new Flash();
		usb.start();
		
		System.out.println("Details of specific transmission data");
		
		usb.stop();
	}
	
	
}

interface USB{
	//Constant: defines the length, width, maximum and minimum transmission speed, etc
	
	void start();
	
	void stop();
	
}

class Flash implements USB{

	@Override
	public void start() {
		System.out.println("U Disc opening operation");
	}

	@Override
	public void stop() {
		System.out.println("U Disk end work");
	}
	
}

class Printer implements USB{
	@Override
	public void start() {
		System.out.println("Printer on");
	}

	@Override
	public void stop() {
		System.out.println("Printer finished working");
	}
	
}

proxy pattern

Can't see the real character

public class StaticProxyTest {

	public static void main(String[] args) {
		Proxy s = new Proxy(new RealStar());
		s.confer();
		s.signContract();
		s.bookTicket();
		s.sing();
		s.collectMoney();
	}
}

interface Star {
	void confer();// interview

	void signContract();// sign a contract

	void bookTicket();// booking

	void sing();// sing

	void collectMoney();// Collect money
}
//Proxy class
class RealStar implements Star {

	public void confer() {
	}

	public void signContract() {
	}

	public void bookTicket() {
	}

	public void sing() {
		System.out.println("Star: singing~~~");
	}

	public void collectMoney() {
	}
}

//proxy class
class Proxy implements Star {
	private Star real;

	public Proxy(Star real) {
		this.real = real;
	}

	public void confer() {
		System.out.println("Broker interview");
	}

	public void signContract() {
		System.out.println("Broker sign contract");
	}

	public void bookTicket() {
		System.out.println("Broker Booking");
	}

	public void sing() {
		real.sing();
	}

	public void collectMoney() {
		System.out.println("Brokers collect money");
	}
}

Factory mode (ignore first)

practice

/*
 * 
 * JDK8: In addition to defining global constants and abstract methods, you can also define static methods and default methods
 * 
 */
public interface CompareA {
	
	//Static method
	public static void method1(){
		System.out.println("CompareA:Beijing");
	}
	//Default method
	public default void method2(){
		System.out.println("CompareA: Shanghai");
	}
	
	default void method3(){
		System.out.println("CompareA: Shanghai");
	}
}
public class SubClassTest {
	
	public static void main(String[] args) {
		SubClass s = new SubClass();
		
		//Knowledge point 1: static methods defined in the interface can only be called through the interface.
//		s.method1();
//		SubClass.method1();
		CompareA.method1();
		//Knowledge point 2: by implementing the object of the class, you can call the default method in the interface.
		//If the implementation class overrides the default method in the interface, the overridden method will still be called
		s.method2();
		//Knowledge point 3: if the parent class inherited by the subclass (or implementation class) and the implemented interface declare a default method with the same name and parameter,
		//If the subclass does not override this method, it will call the method with the same name and parameter in the parent class by default. -- > Class priority principle
		//Knowledge point 4: if the implementation class implements multiple interfaces and default methods with the same name and parameters are defined in these interfaces,
		//If the implementation class does not override this method, an error will be reported. -- > Interface conflict.
		//This requires that we must override this method in the implementation class
		s.method3();
		
	}
	
}

class SubClass extends SuperClass implements CompareA,CompareB{
	
	public void method2(){
		System.out.println("SubClass: Shanghai");
	}
	
	public void method3(){
		System.out.println("SubClass: Shenzhen");
	}
	
	//Knowledge point 5: how to call the parent class in the subclass (or implementation class) method and the method to be rewritten in the interface.
	public void myMethod(){
		method3();//Call your own defined overridden method
		super.method3();//Called is declared in the parent class
		//Call the default method in the interface
		CompareA.super.method3();
		CompareB.super.method3();
	}
}

Inner class

/*
 * Inner member of class 5: inner class
 * 1. Java Class A is allowed to be declared in another class B, then class A is the inner class, and class B is called the outer class
 * 
 * 2.Classification of internal classes: member internal classes (static and non static) vs local internal classes (within methods, code blocks and constructors)
 * 
 * 3.Member inner class:
 * 		On the one hand, as a member of an external class:
 * 			>Calling the structure of an external class
 * 			>Can be modified by static
 * 			>It can be modified by four different permissions
 * 
 * 		On the other hand, as a class:
 * 			> Properties, methods, constructors, etc. can be defined within a class
 * 			> Can be modified by final to indicate that this class cannot be inherited. The implication is that you can inherit without using final
 * 			> Can be modified by abstract
 * 
 * 
 * 4.Focus on the following three issues
 *   4.1 How to instantiate an object of a member's inner class
 * 		//Create a Dog instance (static member inner class):
		Person.Dog dog = new Person.Dog();
		dog.show();
		//Create a Bird instance (non static member inner class):
//		Person.Bird bird = new Person.Bird();//FALSE
		Person p = new Person();
		Person.Bird bird = p.new Bird();
		bird.sing();
 *   4.2 How to distinguish the structure of calling external classes in member internal classes
 * 
 *   4.3 See InnerClassTest1.java for the use of local internal classes during development
 * 
 */

Member inner class

Local inner class

	//Returns an object of a class that implements the Comparable interface
	public Comparable getComparable(){
		
		//Create a class that implements the Comparable interface: a local inner class
		//Mode 1:
//		class MyComparable implements Comparable{
//
//			@Override
//			public int compareTo(Object o) {
//				return 0;
//			}
//			
//		}
//		
//		return new MyComparable();
		
		//Method 2: anonymous local inner class
		return new Comparable(){

			@Override
			public int compareTo(Object o) {
				return 0;
			}
			
		};
		
	}

abnormal

Common anomalies

/*
 * 1, Exception architecture
 * 
 * java.lang.Throwable
 * 		|-----java.lang.Error:Generally, targeted code is not written for processing.
 * 		|-----java.lang.Exception:You can handle exceptions
 * 			|------Compile time exception (checked)
 * 					|-----IOException
 * 						|-----FileNotFoundException
 * 					|-----ClassNotFoundException
 * 			|------Runtime exception (unchecked,RuntimeException)
 * 					|-----NullPointerException
 * 					|-----ArrayIndexOutOfBoundsException
 * 					|-----ClassCastException
 * 					|-----NumberFormatException
 * 					|-----InputMismatchException
 * 					|-----ArithmeticException
 * 
 * 
 * 
 * Interview question: what are the common exceptions? Examples
 */
public class ExceptionTest {
	
	//******************The following are compile time exceptions***************************
	@Test
	public void test7(){
//		File file = new File("hello.txt");
//		FileInputStream fis = new FileInputStream(file);
//		
//		int data = fis.read();
//		while(data != -1){
//			System.out.print((char)data);
//			data = fis.read();
//		}
//		
//		fis.close();
		
	}
	
	//******************The following are runtime exceptions***************************
	//ArithmeticException
	@Test
	public void test6(){
		int a = 10;
		int b = 0;
		System.out.println(a / b);
	}
	
	//InputMismatchException
	@Test
	public void test5(){
		Scanner scanner = new Scanner(System.in);
		int score = scanner.nextInt();
		System.out.println(score);
		
		scanner.close();
	}
	
	//NumberFormatException
	@Test
	public void test4(){
		
		String str = "123";
		str = "abc";
		int num = Integer.parseInt(str);
		
		
		
	}
	
	//ClassCastException
	@Test
	public void test3(){
		Object obj = new Date();
		String str = (String)obj;
	}
	
	//IndexOutOfBoundsException
	@Test
	public void test2(){
		//ArrayIndexOutOfBoundsException
//		int[] arr = new int[10];
//		System.out.println(arr[10]);
		//StringIndexOutOfBoundsException
		String str = "abc";
		System.out.println(str.charAt(3));
	}
	
	//NullPointerException
	@Test
	public void test1(){
		
//		int[] arr = null;
//		System.out.println(arr[3]);
		
		String str = "abc";
		str = null;
		System.out.println(str.charAt(0));
		
	}
	
	
}

try...catch

/*
 * 1, Exception handling: grab and throw model
 * 
 * Process 1: "throwing": once an exception occurs during the normal execution of the program, an object corresponding to the exception class will be generated at the exception code.
 *           And throw this object.
 *           Once the object is thrown, the subsequent code is no longer executed.
 * 		
 * 		Generation of abnormal objects: ① abnormal objects automatically generated by the system
 * 					 ② Manually generate an exception object and throw it
 * 
 * Process 2: "catch": it can be understood as the exception handling method: ① try catch finally ② throws
 * 
 * 
 * 2, Use of try catch finally
 * 
 * try{
 * 		//Possible exception codes
 * 
 * }catch(Exception type 1 (variable name 1){
 * 		//How to handle exceptions 1
 * }catch(Exception type 2 (variable name 2){
 * 		//How to handle exceptions 2
 * }catch(Exception type 3 (variable name 3){
 * 		//How to handle exceptions 3
 * }
 * ....
 * finally{
 * 		//Code that must execute
 * }
 * 
 * explain:
 * 1. finally Is optional.
 * 2. try is used to wrap the possible exception code. In case of an exception during execution, an object corresponding to the exception class will be generated according to this object
 *    To match the type in catch
 * 3. Once the exception object in the try matches a catch, it enters the catch for exception processing. Once the processing is complete, the current
 *    try-catch Structure (without writing finally). Continue to execute the following code
 * 4. catch If the exception type in has no child parent relationship, it doesn't matter who declares it on and who declares it under.
 *    catch If the exception type in satisfies the child parent relationship, the child class must be declared on the parent class. Otherwise, an error is reported
 * 5. Common exception object handling methods: ① string getmessage() ② printStackTrace()
 * 6. Variables declared in the try structure cannot be called after the try structure is created (they can be defined before ry)
 * 7. try-catch-finally Structures can be nested
 * 
 * Experience 1: use try catch finally to handle compile time exceptions, so that the program will no longer report errors at compile time, but errors may still be reported at run time.
 *     It is equivalent to using try catch finally to delay an exception that may occur during compilation until it occurs at run time.
 *     
 * Experience 2: in development, since runtime exceptions are common, we usually don't write try catch finally for runtime exceptions.
 *      For compile time exceptions, we say we must consider exception handling.
 */

finally

/*
 * try-catch-finally Use of finally in:
 * 
 * 
 * 1.finally Is optional
 * 
 * 2.finally What is declared in is the code that must be executed. Even if an exception occurs again in catch, there is a return statement in try and a return statement in catch
 * return Statements, etc.
 * 
 * 3.Resources such as database connection, input / output stream and network programming Socket cannot be recycled automatically by the JVM. We need to recycle resources manually
 *   Release. At this time, the resource release needs to be declared in finally.
 * 
 * 
 * 
 */

throws

/*
 * Exception handling method 2: throws + exception type
 * 
 * 1. "throws + The exception type '' is written at the declaration of the method. Indicates the type of exception that may be thrown when the method is executed.
 *     Once an exception occurs during the execution of the method body, an object of exception class will still be generated at the exception code. After this object meets the throws exception
 *     Type is thrown. Exception code and subsequent code will not be executed!
 *     
 * 2. Experience: try catch finally: the exception is really handled.
 *        throws The only way is to throw the exception to the caller of the method. The exception is not really handled.  
 * 
 * 3. How to choose whether to use try catch finally or throws in development?
 *   3.1 If the overridden method in the parent class does not handle exceptions in the throw mode, the overridden method of the child class cannot use throws, which means that if
 *       There are exceptions in the methods overridden by subclasses, which must be handled in a try catch finally manner.
 *   3.2 In the executed method a, several other methods are called successively, which are executed in a progressive relationship. We recommend using throws for these methods
 *       In a way. For the executed method a, try catch finally can be considered.
 * 
 */
/*
 * One of the rules for method overrides:
 * The exception type thrown by the method overridden by the subclass is not greater than the exception type thrown by the method overridden by the parent class
 * 
 * 
 */

thorw - throw exception manually

Exception : Checked exception, this exception is mandatory for us catch or throw Exception of. When you encounter this exception, you must catch or throw,If it is not processed, the compiler will report an error. For example: IOException. 

RuntimeException: Runtime exceptions, which we do not need to handle, are completely taken over by the virtual machine. For example, we often NullPointerException,We don't do it when we write programs catch or throw. RuntimeException Also inherited from Exception Yes, but the virtual machine distinguishes the two exceptions
/*
 * How to customize exception classes?
 * 1. Inherited from the existing Exception structure: RuntimeException, Exception
 * 2. Provide global constant: serialVersionUID
 * 3. Provides overloaded constructors
 * 
 */
public class MyException extends Exception{
	
	static final long serialVersionUID = -7034897193246939L;
	
	public MyException(){
		
	}
	
	public MyException(String msg){
		super(msg);
	}
}

Keywords: Java

Added by inkdrop on Tue, 21 Dec 2021 04:56:52 +0200