object-oriented programming

Process oriented & object oriented

  • Process oriented thought
    • The steps are clear and simple. What to do in the first step and what to do in the second step
    • Facing the process, it is suitable to deal with some relatively simple problems
  • Object oriented thought
    • Birds of a feather flock together in a classified thinking mode. When thinking about problems, we will first solve what classifications are needed, and then think about these classifications separately. Finally, the process oriented thinking is carried out on the details under a certain classification
    • Object oriented is suitable for dealing with complex problems and problems requiring multi person cooperation!
  • For describing complex things, in order to grasp them macroscopically and analyze them reasonably as a whole, we need to use object-oriented thinking to analyze the whole system. But when it comes to micro operation, it still needs process oriented thinking to deal with it

What is object oriented

  • Object oriented programming (OOP)
  • The essence of object-oriented programming is to organize code by class and data by object
  • Abstract: programming ideas! Continuous learning makes you enlightened! Practice more and test more ideas in your brain! Practice produces true knowledge~
  • Three characteristics:
    • encapsulation
    • inherit
    • polymorphic
  • From the perspective of epistemology, there are objects first and then classes. Objects are concrete things. Class is abstract, which is the abstraction of objects
  • From the perspective of code operation, there are classes before objects. A class is a template for an object

Review methods and deepening

  • Definition of method

    • Modifier
    • Return type
    • break: jump out of the difference between switch end loop and return
    • Method name: pay attention to the specification and see the meaning of the name
    • Parameter list: (parameter type, parameter name)
    • Exception thrown: questions, explained later
    package com.opp;
    
    import java.io.IOException;
    
    //Demo01 class
    public class Demo01 {
    
        //main method
        public static void main(String[] args) {
    
        }
    
        /*
        Modifier return value type method name (...) {
            //Method body
            return Return value;
        }
         */
        //return ends the method and returns a result
        public String sayHello() {
            return "Hello World!";
        }
    
        public void print() {
            return;
        }
    
        public int max(int a, int b) {
            return a > b ? a : b; //Ternary operator!
        }
    
        public void readFile(String file) throws IOException {
            
        }
    }
    
    
  • Method call: recursion

    • Static method
    • Non static method
    • Formal and argument
    • Value passing and reference passing
    • this keyword
package com.opp;

public class Demo02 {

    public static void main(String[] args) {
        //Instantiate this object new
        //Object type object name = object value;
        Student student = new Student();
        student.say();
    }

    //Loaded with class
    public static void a() {
        //b();
    }

    //Class does not exist until it is instantiated
    public void b() {

    }
}

package com.opp;

//pass by value
public class Demo04 {
    public static void main(String[] args) {
        int a = 1;
        System.out.println(a);

        Demo04.change(a);

        System.out.println(a); //1
    }

    //The return value is null
    public static void change(int a) {
        a = 10;
    }
}

package com.opp;

public class Demo05 {
    public static void main(String[] args) {
        Person person = new Person();

        System.out.println(person.name); //null

        Demo05.change(person);

        System.out.println(person.name);
    }

    public static void change(Person person) {
        //Person is an object: the pointed -- > person person = new person(); This is a specific person who can change attributes!
        person.name = "Blitz";
    }
}

//Defines a Person class with an attribute: name
class Person {
    String name;
}

Relationship between class and object

  • Class is an abstract data type. It is the overall description / definition of a certain kind of things, but it can not represent a specific thing
    • Animals, plants, mobile phones, computers
    • Person class, Pet class, Car class, etc. these classes are used to describe / define the characteristics and behavior of a specific thing
  • Objects are concrete instances of abstract concepts
    • Zhang San is a concrete example of man, and Wang CAI in Zhang San's family is a concrete example of dog
    • It is a concrete instance rather than an abstract concept that can embody the characteristics and functions

Creating and initializing objects

  • Create an object using the new keyword

  • Using the new keyword to create a suitable object, in addition to allocating memory space, it will also initialize the created object by default and call the constructor in the class

  • The constructor in the class also becomes a construction method, which must be called when creating an object. And the constructor has the following two characteristics:

    • 1. Must be the same as the name of the class
    • 2. There must be no return type and void cannot be written
  • Constructors must master

    package com.opp.demo02;
    
    //There should be only one main method in a project
    public class Application {
        public static void main(String[] args) {
    
            //Class: abstract, instantiated
            //Class instantiation will return an object of its own!
            //Student object is a concrete instance of student class!
            Student xm = new Student();
            Student xh = new Student();
    
            xm.name = "Xiao Ming";
            xm.age = 3;
    
            System.out.println(xm.name);
            System.out.println(xm.age);
    
            xh.name = "Xiao Hong";
            xh.age = 3;
            
            System.out.println(xh.name);
            System.out.println(xh.age);
    
        }
    }
    
    
    package com.opp.demo02;
    
    //There should be only one main method in a project
    public class Application {
        public static void main(String[] args) {
    
            //Class: abstract, instantiated
            //Class instantiation will return an object of its own!
            //Student object is a concrete instance of student class!
            Student xm = new Student();
            Student xh = new Student();
    
            xm.name = "Xiao Ming";
            xm.age = 3;
    
            System.out.println(xm.name);
            System.out.println(xm.age);
    
            xh.name = "Xiao Hong";
            xh.age = 3;
            
            System.out.println(xh.name);
            System.out.println(xh.age);
    
        }
    }
    
    
    package com.opp.demo02;
    
    //java ---> class
    public class Person {
    
        //Even if a class doesn't care about anything, it will have a method
        //Display definition constructor
    
        String name;
        int age;
    
    
        //alt + insert
    
        //Instantiation initial value
        //1. Using the new keyword is essentially calling the constructor
        //2. used to initialize values
        public Person() {
    
        }
    
        //Parameterized Construction: once a parameterized construction is defined, the definition must be displayed if there is no parameter
        public Person(String name) {
            this.name = name;
        }
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    }
    
    
    /*
        public static void main(String[] args) {
    
            //new Instantiated an object
            //Person person = new Person();
            Person person = new Person("Blitz", 99);
            
            System.out.println(person.name);
        }
    
        Constructor:
            1.Same as class name
            2.no return value
        effect:
            1.new The essence is to call the constructor
            2.Initializes the value of the object
        Note:
            1.After defining a parameterized construct, if you want to use a parameterless construct, you can define a parameterless construct
    
        Alt + Insert
    
        this. =
     */
    
    
    package com.opp;
    
    import com.opp.demo02.Person;
    import com.opp.demo03.Pet;
    
    //There should be only one main method in a project
    public class Application {
    
        public static void main(String[] args) {
    
            /*
            1.Classes and objects
                A class is a template: abstract, and an object is a concrete instance
            2.method
                Define and call!
            3.Corresponding reference
                Reference type: basic type (8)
                Objects are operated by reference: stack -- > heap (address)
            4.Field member: field attribute
                Default initialization:
                    Number: 0.0
                    char: u0000
                    boolean: false
                    Reference: null
                Modifier attribute type attribute name = attribute value!
            5.Object creation and use
                - You must use the new keyword to create an object, and the constructor Person blitz = new Person();
                - Object's property blitz name
                - Object's method blitz sleep()
            6.Class:
                Static properties
                Dynamic behavior method
    
            Encapsulation, inheritance, polymorphism
             */
        }
    }
    
    

encapsulation

  • The dew that should be exposed, the hide that should be hidden

    • We should pursue "high cohesion and low coupling" in program design. High cohesion means that the internal data operation details of a class are completed by ourselves, and external interference is not allowed; low coupling: only a small number of methods are exposed for external use
  • Encapsulation (data hiding)

    • Generally, direct access to the actual representation of data in an object should be prohibited, but should be accessed through the operation interface, which is called information hiding
  • It's enough to remember this sentence: property private, get/set

    package com.opp;
    
    import com.opp.demo04.Student;
    
    /*
        1.Improve data protection and program security
        2.Implementation details of hidden code
        3.Unified interface
        4.System maintainability has increased
     */
    public class Application {
    
        public static void main(String[] args) {
            Student s1 = new Student();
    
            s1.setName("Blitz");
    
            System.out.println(s1.getName());
    
            s1.setAge(999); //illegal
            System.out.println(s1.getAge());
        }
    }
    
    /*
        //Class private: private
        public class Student {
        
            //Property private
            private String name; //name
            private int id; //Student number
            private char sex; //Gender
            private int age;
        
            //Provide some methods that can operate this property!
            //Provide some public get and set methods
        
            //get Get this data
            public String getName() {
                return this.name;
            }
        
            //set Set a value for this data
            public void setName(String name) {
                this.name = name;
            }
        
            //alt + insert
        
        
            public int getId() {
                return id;
            }
        
            public void setId(int id) {
                this.id = id;
            }
        
            public char getSex() {
                return sex;
            }
        
            public void setSex(char sex) {
                this.sex = sex;
            }
        
            public int getAge() {
                return age;
            }
        
            public void setAge(int age) {
                if (age > 120 || age < 0) { //wrongful
                    this.age = 3;
                }else {
                    this.age = age;
                }
        
            }
        }
     */
    
    

inherit

  • The essence of inheritance is to abstract a group of classes, so as to realize better modeling of the real world

  • Extensions means "extension". A subclass is an extension of a parent class

  • JAVA classes only have single inheritance, not multiple inheritance!

  • Inheritance is a relationship between classes. In addition, the relationships between classes include dependency, composition, aggregation and so on

  • Two classes of inheritance relationship, one is a child class (derived class) and the other is a parent class (base class). The subclass inherits the parent class and is represented by the keyword extends

  • In a sense, there should be a "is a" relationship between subclasses and superclasses

  • object class

  • super

  • Method rewrite

    package com.opp.demo05;
    
    //In Java, all classes inherit the Object class directly or indirectly by default
    //Person: parent class
    public class Person /*extends Object*/ {
    
        //public
        //protected
        //default
        //private
        public int money = 10_0000_0000;
    
        public void say() {
            System.out.println("Said a word");
        }
    }
    
    
    package com.opp.demo05;
    
    //Student is person: derived class, subclass
    //The subclass inherits the father and will have all the methods of the father!
    public class Student extends Person {
    
        //Ctrl + H
    
    }
    
    
    package com.opp.demo05;
    
    //Teacher is: derived class, subclass
    public class Teacher extends Person {
    }
    
    
    package com.opp;
    
    
    import com.opp.demo05.Student;
    
    public class Application {
    
        public static void main(String[] args) {
    
            Student student = new Student();
            student.say();
            System.out.println(student.money);
    
        }
    }
    
    
    package com.opp.demo05;
    
    //In Java, all classes inherit the Object class directly or indirectly by default
    //Person: parent class
    public class Person /*extends Object*/ {
    
        public Person() {
            System.out.println("Person No participation");
        }
    
        protected String name = "blitz";
    
        //Private things cannot be inherited!
        public void print() {
            System.out.println("Person");
        }
    }
    
    
    package com.opp.demo05;
    
    //Student is person: derived class, subclass
    //The subclass inherits the father and will have all the methods of the father!
    public class Student extends Person {
    
        public Student() {
            //Hidden code: the parameterless construction of the parent class is called
            super(); //Calling the constructor of the parent class must be in the first line of the subclass constructor
            System.out.println("Student No participation");
        }
    
        private String name = "kk";
    
        public void print() {
            System.out.println("Student");
        }
    
        public void test1() {
            print();
            this.print();
            super.print();
        }
    
        public void test(String name) {
            System.out.println(name);
            System.out.println(this.name);
            System.out.println(super.name);
        }
    
    }
    
    
    package com.opp.demo05;
    
    //Teacher is: derived class, subclass
    public class Teacher extends Person {
    }
    
    
    note:
    super Note:
        1.super The constructor of the parent class must be called in the first instance of the constructor
        2.super Must only appear in subclass method or constructor!
        3.super and this Constructor cannot be called at the same time!
    
    Vs this: 
        The objects represented are different:
            this: The object itself is the caller
            super: Represents the application of the parent object
        premise
            this: Can be used without inheritance
            super: Can only be used under inheritance conditions
        Construction method
            this(): Construction of this class
            super(): Construction of parent class!
    
    Rewriting: inheritance relationship is required. The subclass rewrites the method of the parent class!
        1.Method names must be the same
        2.The parameter list must be the same
        3.Modifier: the scope can be expanded: public > protected > default > private
        4.Exception thrown: the scope can be reduced, but not expanded: ClassNotFoundException --> Exception(large)
    
    Override, the method of the subclass and the parent class must be consistent, and the method body is different!
    
    Why rewrite:
        1.Function of parent class: subclasses are not necessarily required or satisfied!
        Alt + Insert: Override
    
    package com.opp.demo05;
    
    //inherit
    public class A extends B {
    
        //Override override
        @Override //Comments: functional comments!
        public void test() {
            System.out.println("A=>test()");
        }
    }
    
    
    package com.opp.demo05;
    
    //Rewriting is the rewriting of methods, which has nothing to do with properties
    public class B {
    
        public void test() {
            System.out.println("B=>test()");
        }
    }
    
    

polymorphic

  • Dynamic compilation: Type: extensibility

  • That is, the same method can adopt many different behavior modes according to different sending objects

  • The actual type of an object is determined, but there are many types of references that can point to the object

  • Conditions for the existence of polymorphism

    • There is an inheritance relationship
    • Subclass overrides parent method
    • A parent class reference points to a child class object
  • Note: polymorphism is the polymorphism of methods, and there is no polymorphism of attributes

  • instanceof (type conversion) refers to the type and determines what type an object is

    package com.opp.demo06;
    
    public class Person {
    
        public void run() {
            System.out.println("run");
        }
    
    }
    
    /*
    Precautions:
    1.Polymorphism is the polymorphism of methods, and there is no polymorphism of attributes
    2.The parent and child classes have connection type conversion exceptions! ClassCastException!
    3.Existence conditions: inheritance relationship, method needs to be rewritten, and parent class reference points to child class object! Father f1 = new Son();
    
        1.static Method, which belongs to class, does not belong to instance
        2.final constant
        3.private method
     */
    
    
    package com.opp.demo06;
    
    public class Student extends Person {
    
        @Override
        public void run() {
            System.out.println("son");
        }
    
        public void eat() {
            System.out.println("eat");
        }
    }
    
    
    package com.opp;
    
    import com.opp.demo06.Person;
    import com.opp.demo06.Student;
    
    public class Application {
    
        public static void main(String[] args) {
    
            //The actual type of an object is determined
            //new Student();
            //new Person();
    
    
            //The type of reference that can be pointed to is uncertain: the reference of the parent class points to the child class
    
            //The methods that students can call are their own or inherit the parent class!
            Student s1 = new Student();
            //The Person parent type can point to subclasses, but cannot call methods unique to subclasses
            Person s2 = new Student();
            Object s3 = new Student();
    
            //The methods that can be executed by the object mainly depend on the type on the left of the object, which has little to do with the right!
            ((Student) s2).eat(); //The subclass overrides the method of the parent class and executes the method of the subclass
            s1.eat();
    
        }
    }
    
    
    package com.opp.demo06;
    
    public class Person {
        public void run() {
            System.out.println("run");
        }
    }
    
    package com.opp.demo06;
    
    public class Student extends Person {
        public void go() {
            System.out.println("go");
        }
    }
    
    /*
        //Object > String
            //Object > Person > Teacher
            //Object > Person > Student
            Object object = new Student();
    
            //System.out.println(X instanceof Y); //Can it be compiled! Interface
    
            System.out.println(object instanceof Student); //true
            System.out.println(object instanceof Person); //true
            System.out.println(object instanceof Object); //true
            System.out.println(object instanceof Teacher); //false
            System.out.println(object instanceof String); //false
    
            System.out.println("================");
    
            Person person = new Student();
    
            System.out.println(person instanceof Student); //true
            System.out.println(person instanceof Person); //true
            System.out.println(person instanceof Object); //true
            System.out.println(person instanceof Teacher); //false
            //System.out.println(person instanceof String); //Compilation error!
    
            System.out.println("=======================");
    
            Student student = new Student();
    
            System.out.println(student instanceof Student); //true
            System.out.println(student instanceof Person); //true
            System.out.println(student instanceof Object); //true
            //System.out.println(student instanceof Teacher); //Compilation error!
            //System.out.println(student instanceof String); //Compilation error!
     */
    
    
    package com.opp.demo06;
    
    public class Teacher extends Person {
    }
    
    
    package com.opp;
    
    import com.opp.demo06.Person;
    import com.opp.demo06.Student;
    import com.opp.demo06.Teacher;
    
    public class Application {
    
        public static void main(String[] args) {
            //Conversion between types: parent and child
    
            //If you convert a subclass to a parent class, you may lose some of your original methods!
            Student student = new Student();
            student.go();
            Person person = student;
    
    
        }
    }
    
    /*
    1.The parent class refers to an object that points to a child class
    2.Convert the subclass to the parent class and transform upward
    3.Convert a parent class to a child class and transform downward: Cast
    4.Convenient method call and reduce duplicate code! concise
    
    Abstract: encapsulation, inheritance, polymorphism! Abstract class, interface
     */
    
    
    package com.opp.demo07;
    
    public class Person {
    
        //2: Assign initial value
        {
            System.out.println("Anonymous code block");
        }
    
        //1: Execute only once
        static {
            System.out.println("Static code block");
        }
    
        //3
        public Person() {
            System.out.println("Construction method");
        }
    
        public static void main(String[] args) {
            Person person1 = new Person();
            System.out.println("===============");
            Person person2 = new Person();
        }
    }
    
    
    package com.opp.demo07;
    
    //static
    public class Student {
    
        private static int age; //Static variable
        private double score; //Non static variable
    
        public void run() {
    
        }
    
        public static void go() {
    
        }
    
        public static void main(String[] args) {
            go();
        }
    }
    
    
    package com.opp.demo07;
    
    //Static import package
    
    import static java.lang.Math.random;
    import static java.lang.Math.PI;
    
    public class Test {
    
        public static void main(String[] args) {
            System.out.println(random());
            System.out.println(PI);
        }
    }
    
    

abstract class

  • The abstract modifier can be used to modify a method or a class. If you modify a method, the method is an abstract method; If you modify a class, it is an abstract class

  • Abstract classes can have no abstract methods, but classes with abstract methods must be declared as abstract classes

  • Abstract classes cannot use the new keyword to create objects. It is used to let subclasses inherit

  • Abstract methods have only method declarations and no method implementations. They are used to implement subclasses

  • If the subclass inherits the abstraction, it must implement the abstract methods that the abstract class does not implement, otherwise the subclass must also be declared as an abstract class

    package com.opp.demo08;
    
    //Abstract abstract class: class extensions: single inheritance ~ (interfaces can inherit multiple)
    public abstract class Action {
    
        //Constraint ~ someone helped us achieve it~
        //Abstract abstract abstract method has only method name and no method implementation
        public abstract void doSomething();
    
        //1. You can't use the abstract class new. You can only rely on subclasses to implement: constraints!
        //2. Ordinary methods can be written in abstract classes~
        //3. Abstract methods must be in abstract classes~
        //Abstract: Constraints~
    
        //Thinking questions? new, is there a constructor?
        //Abstract the meaning of existence ~ improve development efficiency
    
    }
    
    
    package com.opp.demo08;
    
    //All methods of an abstract class that inherit its subclasses must implement its methods ~ unless the subclass is also abstract
    public class A extends Action {
    
        @Override
        public void doSomething() {
    
        }
    }
    
    

Interface

  • Common class: only concrete implementation

  • Abstract classes: concrete implementations and specifications (abstract methods) are available!

  • Interface: only specification! I can't write my own method. Professional constraints and implementation are separated: mm interface oriented programming~

  • An interface is a specification, which defines a set of rules that embody the idea of "if you are... You must be able to..." in the real world. If you are an angel, you must be able to fly. If you are a car, you must be able to run. If you are a good person, you must kill the bad person; if you are a bad person, you must bully the good person

  • The essence of interface is contract, just like the law between us. After making it, everyone must abide by it

  • The essence of OO is the abstraction of objects. The interface can best reflect this. Why we discuss design patterns only for languages with abstract ability (such as C + +, java, c# etc.) is because what design patterns study is actually how to abstract reasonably

    package com.opp.demo09;
    
    import java.util.Timer;
    
    //Abstract class: Extensions~
    //Class can implement the implements interface
    //If you are a class with an interface, you need to rewrite the methods in the interface~
    
    //Multi inheritance ~ realize multi inheritance by using interface~
    public class UserServiceImpl implements UserService, TimeService {
        @Override
        public void add(String name) {
    
        }
    
        @Override
        public void delete(String name) {
    
        }
    
        @Override
        public void update(String name) {
    
        }
    
        @Override
        public void query(String name) {
    
        }
    
        @Override
        public void timer() {
    
        }
    }
    
    
    package com.opp.demo09;
    
    //Abstract thinking ~ Java
    
    //The keywords defined by interface and interfaces need to have implementation classes
    public interface UserService {
    
        //Constant ~ public static final
        int AGE = 99;
    
        //All definitions in the interface are abstract public abstract
        void add(String name);
    
        void delete(String name);
    
        void update(String name);
    
        void query(String name);
    }
    
    
    package com.opp.demo09;
    
    public interface TimeService {
        void timer();
    }
    
    
    Note:
    effect:
        1.constraint
        2.Define some methods for different people to implement~ 10 ---> 1
        3.public abstract
        4.public static final
        5.Interface cannot be instantiated~ There is no constructor in the interface~
        6.implements Multiple interfaces can be implemented
        7.You must override the methods in the interface~
        8.Summary blog~
    

Inner class

  • For example, if class A is defined as an internal class, then class B is defined as an internal class relative to class A

  • 1. Member internal class

  • 2. Static internal class

  • 3. Local internal class

  • 4. Anonymous inner class

    package com.opp.demo10;
    
    public class Outer {
        private int id = 10;
    
        public void out() {
            System.out.println("This is the method of an external class");
        }
    
        public class Inner {
            public void in() {
                System.out.println("This is an inner class");
            }
    
            //Get the private properties of the external class~
            public void getID() {
                System.out.println(id);
            }
        }
    }
    
    
    package com.opp;
    
    import com.opp.demo10.Outer;
    
    public class Application {
    
        public static void main(String[] args) {
            //new
    
            Outer outer = new Outer();
            //Instantiate the inner class through this outer class~
            Outer.Inner inner = outer.new Inner();
            inner.getID();
        }
    }
    
    package com.opp.demo10;
    
    public class Outer {
    
        //Local inner class
        public void method() {
            class Inner {
    
            }
        }
    
    }
    
    
    
    
    package com.opp.demo10;
    
    public class Test {
        public static void main(String[] args) {
            //There is no name to initialize the class, so there is no need to save the instance to the variable
            new Apple().eat();
    
            new UserService() {
    
                @Override
                public void hello() {
    
                }
            };
        }
    }
    
    class Apple {
        public void eat() {
            System.out.println("1");
        }
    }
    
    interface UserService {
        void hello();
    }
    
    

What is an exception

  • In actual work, the situation encountered cannot be very perfect. For example: for a module you write, the user input does not necessarily meet your requirements, your program wants to open a file, the file may not exist or the file format is wrong, you want to read the data in the database, the data may be empty, etc. Our program is running. The memory or hard disk may be full. wait
  • During the operation of software programs, it is very likely to encounter these abnormal problems just mentioned. We call them exceptions, which means exceptions. These, exceptions, or exceptions, how to make the program we write deal with reasonably. Without the program crashing
  • Exceptions refer to various unexpected conditions during program operation, such as file missing, network connection failure, illegal parameters, etc
  • The exception occurs during the program running, which affects the normal program execution process

Simple classification

  • To understand how Java exception handling works, you need to master the following three types of exceptions:
  • Exception Handling Framework
  • Checking exceptions: the most representative checking exceptions are those caused by user errors or problems, which cannot be foreseen by programmers. For example, when you want to open a file that does not exist, an exception occurs. These exceptions cannot be simply ignored at compile time
  • Runtime exceptions: runtime exceptions are exceptions that may be avoided by programmers. In contrast to checking exceptions, runtime exceptions can be ignored at compile time
  • ERROR: ERROR is not an exception, but a problem out of the control of the programmer. Errors are usually ignored in code. For example, when the stack overflows, an ERROR occurs and they cannot be checked when recompiling

Exception architecture

  • Java treats exceptions as objects and defines a base class java Lang. throwable is the superclass of all exceptions
  • Moreover, many Exception classes have been defined in the Java API. These Exception classes are divided into two categories: ERROR and Exception

Error

  • The Error class is generated and thrown by the Java virtual machine. Most errors have nothing to do with the operation performed by the coder
  • Java virtual machine running error. When the JVM no longer has the memory resources required to continue the operation, OutOfMemoryError will appear. When these exceptions occur, the Java virtual machine (JVM) will generally choose thread termination
  • In addition, when the virtual machine attempts to execute the application, such as NoClassDefFoundError and LinkageError. These errors are not traceable because they are outside the control and processing power of the application, and most of them are not allowed when the program is running

Exception

  • There is an important subclass RuntimeException (runtime Exception) in the Exception branch
    • ArrayIndexOutOfBoundsException (array subscript out of bounds)
    • NullPointerException (null pointer exception)
    • ArithmeticException (arithmetic exception)
    • MissingResourceException (missing resource)
    • ClassNotFoundException (class not found) and other exceptions. These exceptions are not checked. The program can choose to capture and handle them or not
  • These exceptions are generally caused by program logic errors, and the program should avoid such exceptions as much as possible from a logical point of view
  • The difference between Error and Exception: Error is usually a catastrophic and fatal Error that cannot be controlled and handled by the program. When these exceptions occur, the Java virtual machine (JVM) will generally choose to terminate the thread; Exceptions can usually be handled by the program, and these exceptions should be handled as much as possible in the program

Exception handling mechanism

  • Throw exception

  • Catch exception

  • Five keywords of exception handling

    • try,catch,finally,throw,throws
    • Shortcut keys: Ctrl + Alt + T
    package com.exception;
    
    public class Test {
    
        public static void main(String[] args) {
    
            int a = 1;
            int b = 0;
    
            //Suppose you want to catch multiple exceptions: from small to large!
    
            try {//try monitoring area
    
                if (b == 0) {//Actively throw throws exceptions
                    throw new ArithmeticException(); //Actively throw an exception
                }
    
            } catch (Error e) {//Catch (the type of exception you want to catch)
                System.out.println("Error");
            } catch (Exception e) {
                System.out.println("Exception");
            } catch (Throwable t) {
                System.out.println("Throwable");
            } finally {//Deal with the aftermath
                System.out.println("finally");
    
                //Finally, No. finally, assume that IO, resource, and shutdown!
            }
    
    
        }
    
        public void a() {
            b();
        }
    
        public void b() {
            a();
        }
    }
    
    package com.exception;
    
    public class Test {
    
        public static void main(String[] args) {
    
            try {
                new Test().test(1, 0);
            } catch (ArithmeticException e) {
                e.printStackTrace();
            }
    
        }
    
        //Suppose this method cannot handle this exception, and an exception is thrown on the method
        public void test(int a, int b) throws ArithmeticException {
            if (b == 0) {//Actively throw throws exceptions
                throw new ArithmeticException(); //Actively throw exceptions, which are generally used in methods
            }
            System.out.println(a / b);
        }
    }
    

Custom exception

  • Using Java's built-in Exception class can describe most of the exceptions that occur during programming. In addition, users can customize exceptions. You can customize the Exception class by inheriting the Exception class

  • Using custom exception classes in programs can be roughly divided into the following steps:

    • Create custom exception class
    • Throw an exception object through the throw keyword in the method
    • If the exception is handled in the method that throws the exception at present, you can use the try catch statement to catch and handle it; Otherwise, use the throw keyword at the method declaration to indicate the exception to be thrown to the method caller, and continue with the next operation
    • Catch and handle exceptions in the caller of the exception method
    package com.exception;
    
    //Custom exception class
    public class MyException extends Exception {
    
        //Transfer number > 10;
        private int detail;
    
        public MyException(int a) {
    
            this.detail = a;
        }
    
        //toString: abnormal print information
        @Override
        public String toString() {
            return "MyException{" +
                    "detail=" + detail +
                    '}';
        }
    }
    
    
    package com.exception;
    
    public class Test {
    
        //There may be abnormal methods
    
        static void test(int a) throws MyException {
    
            System.out.println("The parameters passed are:" + a);
    
            if (a > 10) {
                throw new MyException(a); //Throw
            }
    
            System.out.println("OK");
        }
    
        public static void main(String[] args) {
            try {
                test(11);
            } catch (MyException e) {
                System.out.println("Myexception=>" + e);
            }
        }
    }
    
    

Experience summary in practical application

  • When dealing with runtime exceptions, logic is used to reasonably avoid and assist in try catch processing
  • After multiple catch blocks, you can add a catch (Exception) to handle exceptions that may be missed
  • For uncertain code, you can also add try catch to handle potential exceptions
  • Try to handle exceptions. Remember to simply call printStackTrace() to print out
  • How to handle exceptions should be determined according to different business requirements and exception types
  • Try to add finally statement blocks to release the occupied resources. IO~ Scanner~

Tags: Java

Posted by mark123 on Sun, 17 Apr 2022 08:06:41 +0930