JAVA object oriented
Advantages of object orientation:
- Consistent with human thinking, "class" simulates abstract concepts in the real world, and "object" simulates entities in the real world
- Information hiding to improve the maintainability and security of the program: encapsulating the attributes and behaviors of the class in the class to ensure that their modification will not affect other objects and is conducive to maintenance; Encapsulation makes it impossible to access the properties and methods of the object outside the object at will, so as to avoid the influence of external errors and improve the security
- Improve program reusability: a class can create multiple object instances
1, Objects and classes
As an object-oriented language, java supports polymorphism, inheritance, encapsulation, abstraction, class, object, instance, method and overload
Class: a collection of objects with the same properties and methods
Objects: instances of classes
Relationship between class and object: abstract and concrete. A class is the result of comprehensive abstraction of multiple objects. An object is an instance of a class
1. Class
- Define class:
[Access modifier ] class Class name{ //Properties and methods } //1. Access modifiers: public, private, protected //2.class: keyword of declaration class //3. Naming specification: class name is capitalized
- Attributes: characteristics owned by objects
[Access modifier ]Data type property name=Initial value;
- Methods: the behavior of objects performing operations
[Access modifier ]Return type method name(Parameter type parameter 1){ //Method body } //When the return type is void, there is no return value and the "return" keyword is not necessary, but it can be used to exit the method (return;) //When the return type is not void, you must use the "return" keyword to return the corresponding type, otherwise a compilation error will occur //The parameter list can declare multiple parameters, which are separated by "," and can be omitted without passing parameters
2. Object
Class objects can call members of the class, such as class properties and methods
- Create object:
Class name object name=new Class name(); //The left class name is the data type of the object, and the right class name () is the construction method of the class //new is the keyword
- Use object:
Object name.attribute //Properties of the reference object Object name.Method name() //Methods of referencing objects
3. Method
- Method call:
Object name.Method name(Parameter 1,Parameter 2... ,parameter n); //When calling a method, the data type and quantity of formal and actual parameters should be consistent //Call the method in this class: this Method name ();
- Method parameters:
- Class as a method parameter: the object of this class is passed
- Abstract class is used as a method parameter, and the subclass object of the abstract class is passed
- As a method parameter, the interface passes the implementation class object of the interface
- Return value:
- A normal class is used as the return value of the method, and the object of this class is returned
- The abstract class is used as the return value of the method and returns the subclass object of the abstract class
- Interface is used as the return value, which returns the implementation class object of the interface
- Return return value:
- return expression; Leaves the method and returns a value or object of the specified type,
- return ; Directly leave the method without returning a value (generally use void type methods)
1. Definition method:
Access modifier type method name(parameter list){ //Method body }
2. Construction method
The method with the same name as the class has no return value. The main function is to complete the initialization of objects. When a class instantiates an object, it will automatically call the construction method, which can be overloaded.
3. Method overload
- Same name different parameters
- Advantages: if you only need to perform one operation, having the same method name will increase the readability of the program
- You can overload by changing the number of parameters or changing the type of parameters
- Overloading is independent of the return type
4. Method rewriting
- Rewrite the methods inherited from the parent class in the subclass according to the requirements
- Solve the problem: the function of the parent class cannot meet the needs of the child class
- Different classes (parent and child classes) have the same method name, the same parameter and the same return value (or the return value is its subclass)
- Access cannot be reduced
- A static method of a parent class cannot be overridden as a non static method by a subclass, and a non static method of a parent class cannot be overridden as a static method by a subclass
- A subclass can define a static method with the same name as the parent class to hide the static method of the parent class in the subclass (Note: Super cannot be used in static methods)
- Private methods of a parent class cannot be overridden by subclasses and cannot throw more exceptions than those of the parent class
* * * * * the difference between overloading and overriding:
- Overload: involving the method with the same name in the same class. The method name is required to be the same, the parameter list is different, and it has nothing to do with the return value type
- Override: involving methods with the same name between subclasses and parent classes. The method name, parameter list and return value type are required to be the same
Comparison item | position | Method name | Parameter table | Return value | Access modifier |
---|---|---|---|---|---|
rewrite | Subclass | identical | identical | The same or its subclasses | Cannot be more strict than the parent class |
heavy load | similar | identical | inequality | irrelevant | irrelevant |
4.Object class
- The Object class is the parent class of all classes (all classes hide the inherited Object class by default)
- Methods of Object class often overridden by subclasses:
method | explain |
---|---|
toString() | Returns information about the current object itself by string object |
equals() | It returns true to compare whether two objects are the same object |
hashCode() | Returns the hash code value of the object |
getClass() | Get the Class information of the current object and return the Class object |
Package
- Allows classes to form smaller units (similar to folders), making it easy to find and use the corresponding files.
- Prevent naming conflicts and distinguish between classes with the same name
- Help implement access control
//As the first statement of java source code //Declare package with package package Package name;
-
Package naming conventions:
- It is best to prefix the package name with a unique prefix, usually using the network domain name package com zb. mypackage;
- Composed of lowercase letters
- The subsequent parts of the package name vary according to the internal specifications of different organizations (organization name, department name and project name)
-
Import package: use classes that are not in the same package:
import Package name.Class name;
matters needing attention:
- A class references two classes with the same name from different packages at the same time Class name distinction
- Each package is independent, and the top-level package will not contain the classes of sub packages
- package must be on the first line (there is one and only one), followed by import, followed by the declaration of the class
Access modifier
- private: can only be accessed in the same class
- Default modifier: it can be accessed in the same class / package
- protected: can be accessed in the same class / package / subclass
- public: can be accessed anywhere
Static modifier
-
Static variable: it can be accessed directly through the class name
-
Static method: it can be accessed directly through the class name (this / super cannot be used), and must be implemented (main)
Class name.Static variable Class name.Static method()
-
Static code block: when the JVM loads a class, it will execute the code block (multiple static code blocks will be executed in sequence, and each will be executed only once)
Note: static variables cannot be defined in instance methods
2, Inherit extensions
Extensions keyword:
- A subclass can only inherit the properties and methods modified by public and protected in the parent class, regardless of whether the subclass and parent class are in the same package. Only when the subclass and parent are in the same package can they inherit the properties and methods modified by the default permission modifier.
- Cannot inherit private member and constructor of parent class
1. Inheritance method:
class Parent class { } class Subclass extends Parent class { }
-
characteristic:
- Subclasses have non private properties and methods of the parent class.
- Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
- Subclasses can implement the methods of their parent classes in their own way.
- Java inheritance is single inheritance, but it can be multiple inheritance.
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Gu79JwmY-1646633491776)(images/1644915719012.png)]
- It improves the coupling between classes (the disadvantage of inheritance, the higher the coupling degree will cause the closer the connection between codes, the worse the code independence).
Keywords super and this:
-
super: access to parent class members and reference the parent class of the current object.
- Call the parent class constructor
- Call the parent class method (when the child class overrides the parent class method)
be careful:
-
super can only appear in subclass methods and constructors
-
When super calls the constructor, it can only be the first sentence
-
super cannot access private members of a parent class
//Call parent class constructor syntax super(); super(parameter list); //Call parent method syntax super.Method name(parameter list)
-
this: a reference to yourself.
- Call the constructor of the current class, and it must be the first statement of the method. For example: this(); Call the default constructor. This (parameter); Call the construction method with parameters.
- Defines the data field variable of the current object. It is generally used when the local variable in the method has the same name as the data field variable of the object. Such as this num = num. this.num represents the data field variable num of the current object, and num represents the local variable in the method.
class Animal { void eat() { System.out.println("animal : eat"); } } class Dog extends Animal { void eat() { System.out.println("dog : eat"); } void eatTest() { this.eat(); // this calls its own method super.eat(); // super calls the parent class method } } public class Test { public static void main(String[] args) { Animal a = new Animal(); a.eat(); // animal : eat Dog d = new Dog(); d.eatTest(); //dog : eat //animal : eat } }
final keyword
Final keyword declares that a class can be defined as the final class that cannot be inherited; Or used to decorate a method so that it cannot be overridden by subclasses.
//1. Declaration class final class Class name{ //Method body } //2. Declaration method Modifier final Return value type method name(){ //Method body } //Note: instance variables can also be defined as final. Variables defined as final cannot be modified. The method declared as final class is automatically declared as final, but the instance variable is not final
3, Polymorphism
Meaning: the ability of the same behavior to have multiple different forms or forms
(parent and child objects have different methods to implement the same behavior)
Advantages of polymorphism: elimination of coupling relationship between types, replaceability, extensibility, interface, flexibility and simplification
1. Necessary conditions for polymorphism
- Inheritance: in polymorphism, there must be subclasses and parent classes with inheritance relationship.
- Override: subclasses redefine some methods in the parent class. When these methods are called, the subclass's methods will be called.
- The parent class reference points to the child class object (upward transformation): in polymorphism, the reference of the child class needs to be assigned to the parent class object. Only in this way can the reference call both the methods of the parent class and the methods of the child class.
abstract class Animal { //Abstract class abstract void eat(); //Abstract method eat } class Cat extends Animal { //Subclass Cat public void eat() { System.out.println("Eat fish"); //eat } public void work() { System.out.println("Catch a mouse"); } } class Dog extends Animal { //Subclass dog public void eat() { //eat System.out.println("Eat bones"); } public void work() { System.out.println("Housekeeping"); } } //Test class public class Test { public static void main(String[] args) { show(new Cat()); // Call the show method with a Cat object show(new Dog()); // Call the show method with a Dog object Animal a = new Cat(); // Upward transformation a.eat(); // Cat eat is called Cat c = (Cat)a; // Downward transformation c.work(); // Cat work is called } public static void show(Animal a) { a.eat(); // Type judgment if (a instanceof Cat) { // What cats do Cat c = (Cat)a; c.work(); } else if (a instanceof Dog) { // What dogs do Dog c = (Dog)a; c.work(); } } } //When calling a method in a polymorphic way, first check whether the method exists in the parent class. If not, there will be a compilation error; If so, call the method with the same name of the subclass.
be careful:
- Abstract classes are instantiated
- If the subclass is not an abstract class, you must override all abstract methods in the abstract class
- Abstract (abstract class / abstract method) cannot be used with final (final class / non inheritable method)
- Abstract modified abstract method has no method body
- The private keyword cannot modify abstract methods
2. Richter substitution principle
- The subclass can replace the parent class; Or where the parent class appears, the child class can appear, otherwise it cannot;
- reflect:
- Parent type as parameter
- Parent type as return type
3. Upward transformation
- The transformation from a child class to a parent class is called an upward transformation
Parent type reference variable name=new Subtype(); Parent p=new Child();
- Invoking an overriding method by referencing a variable through the parent class will call the method of the child class (polymorphic)
- A subclass specific method cannot be called by referencing a variable through a parent class
4. Downward transformation
- When a parent type is converted to a child type, it becomes a downward transformation, and forced type conversion must be performed
Subtype reference variable name=(Subtype) The name of the parent variable of the reference type; Parent p; Child c=(Child) p;
- Calling the override method will call the method of the subclass (polymorphic)
- Forced type conversion converts a parent class into a subclass, and subclass specific methods can be called
- If it is not converted to a real subclass type, a type conversion exception will appear (use the instanceof operator to judge the type)
public class Pet { //Parent class: pet method: toHospital public void toHospital(){ System.out.println("Pet doctor"); } } public class Dog extends Pet{ //Subclass: dog method: toHospital @Override public void toHospital() { System.out.println("Dog doctor"); } public void eat(){ System.out.println("Feed the dog bones"); } } public class Test { public static void main(String[] args) { System.out.println("Upward transformation"); Pet pet=new Dog(); pet.toHospital(); //Dog doctor pet.eat(); //An error is reported. Subclass specific methods cannot be called System.out.println("Downward transformation"); Dog dog=(Dog) pet; } }
4.instanceof operator
In the process of downward transformation, if it is not converted to a real subclass type, a type conversion exception will occur
When using instanceof, the object type must have a class inheritance relationship with the class specified by the parameters behind instanceof, otherwise the compilation will be wrong
//Parent class: pet method: toHospital public class Pet { public void toHospital(){ System.out.println("Pet doctor"); } } //Subclass: dog rewriting method: toHospital specific method: eat public class Dog extends Pet{ @Override public void toHospital() { System.out.println("Dog doctor"); } public void eat(){ System.out.println("Feed the dog bones"); } } //Subclass: bird rewriting method: toHospital specific method: fly public class Bird extends Pet{ @Override public void toHospital() { System.out.println("Bird doctor"); } public void fly() { System.out.println("Birds can fly"); } } public class Test { public static void main(String[] args) { /* Pet pet=new Dog(); pet.toHospital(); Bird bird=(Bird) pet; //Type conversion exception */ Pet pet=new Bird(); //Pet pet=new Dog(); pet.toHospital(); if(pet instanceof Dog){ Dog dog=(Dog) pet; dog.eat(); }else if(pet instanceof Bird){ Bird bird=(Bird) pet; bird.fly(); } } }
4, Encapsulation
- Encapsulation:
- Wrap and hide the implementation details of the abstract function interface to prevent this kind of code and data from being randomly accessed by the code defined by the external class.
- To access the code and data of this class, it must be controlled through strict interface
- Advantages of packaging:
- Reduce code coupling and improve reminder independence
- The internal structure of the class can be modified freely
- More precise control of member variables to prevent users from modifying properties by mistake
- Hide information and realize details
1. Packaging method
- Modify the visibility of attributes to restrict access to attributes (generally private, to prevent incorrect modification)
public class Person{ private String name; private int age; } //Set name and age to private fields, which can only be accessed by this class
- Create public getter/setter methods (for attribute reading and writing)
- Add attribute control statement in getter/setter method (judge the legitimacy of attribute value)
public class Person{ private String name; private int age; public int getAge(){ return age; } public String getName(){ return name; } public void setAge(int age){ this.age = age; } public void setName(String name){ this.name = name; } }
Note: the public method is the entry for the external class to access the member variables of this class. Any class that wants to access private member variables in the class must pass these getter and setter methods.
public class PersonTest{ public static void main(String args[]){ Person p1 = new Person(); p1.setName("James"); p1.setAge(20); System.out.print("Name:"+p1.getName()+"Age:"+p1.getAge()); } }
5, Abstract class
- Define abstract classes and methods:
public abstract class Class name{ public abstract Method name(); }
- Abstract classes cannot be instantiated, but you can create a reference variable whose type is an abstract class and points to non Abstract subclass instances
- Differences between abstract classes and ordinary classes:
- Abstract classes cannot be instantiated
- Abstract class has no method body
- Use of abstract classes and methods:
- Abstract classes can have no abstract methods, but classes containing abstract methods must be defined as abstract classes
- If the subclass does not implement all the abstract methods of the parent class, the subclass must be defined as an abstract class
- There are no abstract construction methods or abstract static methods.
- Abstract classes can have non Abstract construction methods, which may be called when creating subclass instances
6, Interface
- Interface: a collection of abstract methods (public, defined, and value invariant). It is declared with interface. A class inherits the abstract methods of the interface by inheriting the interface.
- Interface and class: the writing method is similar, but they belong to different concepts; Class describes the attributes and methods of the object, and the interface contains the methods to be implemented by the class; Unless the class implementing the interface is an abstract class, the class should define all methods in the interface.
- Interface implementation: an interface cannot be instantiated, but it can be implemented. The class implementing the interface must implement all methods in the interface, otherwise it must be declared as an abstract class.
- In addition, in Java, interface types can be used to declare a variable. They can become a null pointer or be bound to an object implemented by this interface.
1. Declaration and implementation of interface
Declare interface
[Access modifier ] interface Interface name[extends Other interface names]{ //Declare variables (final,static fields of any type) //Abstract method } //Example: interface Aniaml{ public void eat(); public void travel(); }
Implementation interface
[Access modifier ] class Class name implements Interface 1,Interface 2....,Interface n{ //Method body }
Interface as property
Take the interface as an attribute and call the method of the interface through the attribute
//Interface bird call public interface ShoutAbility { void shout(); } //Abstract bird public abstract class Bird { ShoutAbility shout_ablility; //Birdsong mode (the interface is used as an attribute, and the method in the interface is called through the attribute) //Bird construction method, initialize bird call public Bird(ShoutAbility shout_ablility) { this.shout_ablility = shout_ablility; } //call public void shout(){ shout_ablility.shout(); } }
2. Difference between interface and class
- Interfaces cannot be used to instantiate objects.
- Interface has no constructor
- All methods in the interface must be abstract methods. After Java 8, non abstract methods can be modified with the default keyword in the interface.
- An interface cannot contain member variables, only static and final
- The interface is not inherited by the class, but implemented by the class.
- The implementation class of the interface must implement all methods of the interface
- The interface supports multiple inheritance: implements. Multiple interfaces are separated by ","
3. Interface characteristics
-
Each method in the interface is also implicitly abstract, and the method in the interface will be implicitly specified as public abstract (after JDK 1.9, it is allowed to define the method as private).
-
The interface can contain variables, but the variables in the interface will be implicitly specified as public static final variables (and can only be public. Using private modification will report compilation errors).
-
The methods in the interface cannot be implemented in the interface. The methods in the interface can only be implemented by the class that implements the interface. (after JDK 1.8, there can be static methods and method bodies in the interface.)
-
jdk1. After 8, the interface is allowed to contain specific implementation methods, which are called "default methods", and the default methods are decorated with the default keyword.
-
One interface can inherit another interface, which is similar to the inheritance between classes.
4. Rewrite the interface
- When a class implements the method of an interface, it cannot throw a mandatory exception. It can only throw the mandatory exception in the interface or in the abstract class that inherits the interface.
- Class should maintain consistent method names when overriding methods, and should maintain the same or compatible return value types.
- If the class implementing the interface is an abstract class, there is no need to implement the methods of the interface.
7, Object oriented design principles
Six principles:
- Single responsibility principle - SRP
- Opening and closing principle - OCP
- Chinese style substitution principle - LSP
- Dependency Inversion Principle - DIP
- Interface isolation principle - ISP
- Dimitri principle - LOD
1. Single responsibility principle (SRP)
Single Responsibility Principle
- Definition: there should be and only one class causing class changes (a class only takes on one responsibility)
- advantage:
- The complexity of the class is reduced, and there is a clear definition of what responsibilities to implement;
- The logic becomes simple, the readability of the class is improved, and because the logic is simple, the maintainability of the code is also improved;
- The risk of change is reduced because it will only be modified in a single class.
2. Opening and closing principle (OCP)
Open Closed Principle
-
Definition: a software entity, such as classes, modules and functions, should be open to extension and closed to modification (a software entity should change through extension rather than by modifying existing code)
In the process of coding, when we need to modify the code, we should try our best not to move the original code, and meet the requirements through expansion.
3. Richter substitution principle (LSP)
Liskov Substitution Principle
- Definition: all references to the base class must be able to use the objects of its subclasses transparently. (a subclass can replace the parent class; or where the parent class appears, a subclass can appear; otherwise, it cannot.)
- The Richter substitution principle defines a specification for good inheritance, which contains four layers of meaning:
- Subclasses can implement the abstract methods of the parent class, but they cannot override the non abstract methods of the parent class.
- Subclasses can have their own properties and methods.
- When the subclass overrides or overloads the method of the parent class, the input parameters can be amplified (this method is no longer a method that overrides the parent class)
- When the subclass overrides or overloads the method of the parent class, the output result can be reduced (the return value should be less than or equal to the return value of the method of the parent class)
4. Dependency Inversion Principle (DIP)
-
Definition: the high-level module should not rely on the low-level module, and both should rely on its abstraction, which should not rely on details; Details should rely on abstraction;
Bottom module and high-level module: the inseparable atomic logic is the bottom module, and the reassembly of atomic logic is the high-level module
Abstraction and details: in the Java language, abstraction refers to interfaces or abstract classes, neither of which can be instantiated; The details are the classes generated by implementing interfaces or inheriting abstract classes, that is, the implementation classes that can be instantiated
Dependency inversion principle means that the dependency between modules occurs through abstraction, and there is no direct dependency between implementation classes. Its dependency is realized through interface, which is commonly known as interface oriented programming.
5. Interface isolation principle (ISP)
Interface Segregation Principle
- Definition: the client should not rely on the interface it does not need (the client should provide whatever interface it needs and eliminate the unnecessary interface, which requires refinement of the interface to ensure the purity of the interface. In another way, the dependency relationship between classes should be based on the smallest interface, that is, to establish a single interface)
6. Dimitri principle (LOD)
Law of Demeter
-
Definition: an object should have the least understanding of other objects (only communicate with direct friends)
A class should know the least about the classes it needs to couple or call. The closer the relationship between classes and the greater the degree of coupling, the greater the impact of class changes on its coupled classes. This is also our core design oriented principle: low coupling and high cohesion.
8, Abnormal
1. Exception handling
- The use of exception handling mechanism provides the program with the ability of error handling
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zpcwfTe9-1646633491777)(images/1645580198494.png)]
- Classification: exceptions are divided into Checked exceptions and runtime exceptions:
- Checked exceptions must be caught or declared thrown
- Runtime exceptions do not require that they be caught or declared to be thrown
2. Exception handling keywords
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9PUe1Mmi-1646633491777)(images/1645580246173.png)]
①try-catch
-
Use the try and catch keywords to catch exceptions. try/catch code blocks are placed where exceptions can occur. The code in the try/catch code block is called protection code
-
**(multiple catch blocks) * * try code blocks can be followed by multiple catch code blocks, which is called multiple catch (if the data type throwing an exception is passed in sequence until it is caught or passed through all catch blocks)
- Sequence of catch statements: subclass first and then parent class
- Match one by one in order when exceptions occur
- Execute only the first catch statement that matches the exception type
-
Using the try catch block to catch exceptions can be divided into three cases:
-
Normal: [the transfer of external chain pictures fails, and the source station may have anti-theft chain mechanism. It is recommended to save the pictures and upload them directly (img-NYu2Pw2Z-1646633491779)(images/1645580438232.png)]
-
Exception occurred:
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-u2ju2FkT-1646633491779)(images/1645580474895.png)]
- Exception type mismatch:
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qJBrplfp-1646633491780)(images/1645580672573.png)]
-
-
Exception handling in catch block:
- Add user-defined processing information
System.err.println("An error occurred");
- Call method input exception information
e.printStackTrance();
- Common methods of exception object
method explain void printStackTrace() Output abnormal stack information String getMessage() *Returns an exception information description string, which is part of the output information of printStackTrace()
②Try-catch-finally
-
Add a finally block after the try catch block: execute whether an exception occurs (unless there is an interrupt program code block System.exit(1)) in the catch)
-
There is a try catch finally block of return:
- Whether there are exceptions or not, the code in the finally block will be executed;
- When there is a return in try and catch, finally will still execute;
- Finally is executed after the expression operation after return (at this time, the calculated value is not returned, but the value to be returned is saved first. Regardless of the code in finally, the returned value will not change, but it is still the previously saved value). Therefore, the return value of the function is determined before finally execution;
- It is better not to include return in finally, otherwise the program will exit in advance, and the return value is not the return value saved in try or catch.
//Case 1: try{} catch(){}finally{} return; //Obviously, the program is executed in sequence. Situation 2: try{ return; }catch(){} finally{}return; //The program executes the code before return in the try block (including the expression operation in the return statement); Then execute the finally block, and finally execute the return in the try; The return statement after the finally block will not be executed because the program has returned in the try. //Case 3: try{ } catch(){return;} finally{} return; //The program sequence executes try first. If there is an exception, execute the catch block. ① if there is an exception: execute the code before return in catch (including the expression operation in the return statement), then execute all the codes in the finally statement, and finally execute the return in the catch block After finally, the code at 4 is no longer executed. ② No exception: try and finally return //Case 4: try{ return; }catch(){} finally{return;} //The program executes the code before return in the try block (including the expression operation in the return statement); Then execute the finally block. Because there is a return in the finally block, exit in advance. //Case 5: try{} catch(){return;}finally{return;} //The program executes the code before return in the catch block (including the expression operation in the return statement); Then execute the finally block. Because there is a return in the finally block, exit in advance. //Situation 6: try{ return;}catch(){return;} finally{return;} //The program executes the code before return in the try block (including the expression operation in the return statement); ① There is an exception: execute the code before return in the catch block (including the expression operation in the return statement); Then execute the finally block again. Because there is a return in the finally block, exit in advance. ② No exception: execute the finally block again. Because there is a return in the finally block, exit in advance.
③throw/throws
- In addition to the system automatically throwing exceptions, some problems also require programmers to throw exceptions themselves
- Difference between throw and throws:
- Different functions: throw is used for the programmer to throw an exception, and throws is used to declare that an exception has been thrown in the method
- Different usage positions: throw is located inside the method body and can be used as a separate statement. throws must follow the method parameter list and cannot be used alone
- Different contents: throw throws an exception object, which can only be one. Throws is followed by exception classes, which can be followed by multiple, separated by ",".
throw | throws |
---|---|
Generate and throw an exception | An exception was thrown inside the declared method |
It is located inside the method body and can be used as a separate statement | It must follow the method parameter list and cannot be used alone |
Throw an exception object, and it can only be one | Declare the type of exception thrown, which can be followed by multiple exceptions " |
④ Custom exception
- Define exception class
- Write exception class construction method
- Instantiate the custom exception object and throw it with throw
public class myException extends Exception{ public myException(String message){ super(message); } } //throw is used in the program throw new myException("Custom type error");
3. Common exception types
Exception type | explain |
---|---|
Exception | Parent class of exception hierarchy |
ArithmeticException | An arithmetic error, such as dividing by zero |
ArrayIndexOutOfBoundsException | subscript out of bounds |
NullPointerException | Trying to access a null object member |
ClassNotFoundException | The required class could not be loaded |
IllegalArgumentException | Method received an illegal parameter |
ClassCastException | Object cast error |
NumberFormatException | Abnormal number format conversion, such as converting "abc" to number |