Javase Basics

1. Imagine the object

Three characteristics

encapsulation

_Encapsulation means hiding the properties and implementation details of the object, exposing the interface only to the outside world, and controlling the access level for reading and modifying the properties in the program; Combine the abstracted data with the behavior (or function) to form an organic whole, that is, combine the data with the source code of the operation data to form a "class", where the data and function are members of the class.

  1. Life Case:
    ATM, Wire
  2. Understanding encapsulation in Java:
    Hide something and provide the appropriate way to get it.

Hide the complexity inside the object and only expose simple interfaces to the outside world. Easy to call from outside, so as to improve the scalability and maintainability of the system. As the saying goes, hide the hidden and expose the exposed. This is the design idea of encapsulation.

  1. Benefits of encapsulation: Enhance code security

Code:

public class Girl {//girl
    //Attributes:
    private int age;
    //Reading age:
    public int getAge(){
        return age;
    }
    //Set age:
    public void setAge(int age){
        if(age >= 30 ){
            this.age = 18;
        }else{
            this.age = age;
        }
    }
}

Test method:

public class Test {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //Create an object of the Girl class:
        Girl girl = new Girl();
        /*g.age = 33;
        System.out.println(g.age);*/
        //Set age:
        g.setAge(31);
        //Reading age:
        System.out.println(girl.getAge());
    }
}

The code above modifies private for the attribute age so that access to it is limited. Now I want to add other restrictions, but there is no way to add them on the attribute itself, so we add them by defining a method.
In the case of attributes:
Encapsulate:
(1) Privateize attributes, modified by private s --> add permission modifiers
Once a permission modifier is added, no one else is free to get this property
(2) Provide public decorated methods for others to access/use
(3) Even though the outside world can access the attributes by means of methods, it is not free to access them, because we can add restrictions to the methods.

Deep Practice:
Code:

public class Student {
    //Attributes:
    private int age;
    private String name;
    private String sex;
    //Add the corresponding setter and getter methods:
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        if("male".equals(sex) || "female".equals(sex) ){//sex is male or female
            this.sex = sex;
        }else{
            this.sex = "male";
        }
    }
    //Add a constructor:
    public Student(){
    }
    public Student(int age,String name,String sex){
        this.age = age;
        this.name = name;
        //this.sex = sex;
        this.setSex(sex);
    }
}

Test class:

public class Test {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //Create a Student object:
        Student s1 = new Student();
        s1.setName("Zhang San");
        s1.setAge(19);
        s1.setSex("female");
        System.out.println(s1.getName()+"---"+s1.getAge()+"----"+s1.getSex());//Zhang San--19--Women
        Student s2 = new Student(18,"Li Si","asdfsadf");
        System.out.println(s2.getName()+"---"+s2.getAge()+"----"+s2.getSex());//Li Si--18--Male
    }
}

inherit


Characteristic:

Parent Class:

public class Person {
    //Attributes:
    private int age;
    private String name;
    private double height;
    //Provide a setter getter method:
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getHeight() {
        return height;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    //Method:
    public void eat(){
        System.out.println("You can eat.");
    }
    public void sleep(){
        System.out.println("You can sleep.");
    }
}

Subclass:

public class Student extends Person {//Subclass Student inherits parent Person
    //Attributes:
    private int sno;//School Number
    public int getSno() {
        return sno;
    }
    public void setSno(int sno) {
        this.sno = sno;
    }
    //Method:
    public void study(){
        System.out.println("Students can learn");
    }
}

Test class:

public class Test {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //Create object of subclass Student
        Student s = new Student();
        s.setSno(1001);
        s.setAge(18);
        s.setName("Feifei");
        s.setHeight(180.4);
        System.out.println("The student's name is:"+s.getName()+",Students'age:"+s.getAge());
        //Access method:
        s.study();
        s.eat();
        s.sleep();
    }

Result:

The student's name is: Zhang San, the student's age is 18
Students can learn
You can eat.
You can sleep.


Access characteristics of member methods in inheritance

  1. No duplicate name
  2. Duplicate Name
    See who's new, who's going to start with, and children don't find a parent-child debt to pay off by the parent


Override of method

1. Overview: A subclass has the same method as its parent
2. Access features: see who's new, who calls first, and subclasses don't find a parent
3. Note: @Override-> can detect if this method is an override
4. Prerequisite: The child parent inherits the parent
5. Notes:
. Subclass methods override parent methods and must guarantee that permissions are greater than or equal to those of the parent.
public protected default private
. Subclass methods override parent methods, and return value types, function names, and parameters are identical.
. Private methods cannot be overridden (parent private member subclasses cannot be inherited)
. Subclass methods override parent methods, and methods of subclasses return values if the parent method is worth the subclass or the same

Summary: Method overrides are identical to the parent class.



Access characteristics of inherited sub-parent construction methods



Use of super in inheritance (in subclasses)! [Insert picture description here] ( https://img-blog.csdnimg.cn/2fc628f45c0948bcb03e94e54b847fa7.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQmlnQmlnbWlu,size_20,color_FFFFFF,t_70,g_se,x_16#pic_center) [1] super: refers to: the parent class [2] super can modify attributes, can modify methods; in the method of subclasses, super. attribute super. method can be displayed to invoke attributes provided by the parent class, methods. In general, super. can be omitted from writing:! [Insert picture description here] ( https://img-blog.csdnimg.cn/f9161e71411f41aeb18f5b69fdf01cdc.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBAQmlnQmlnbWlu,size_20,color_FFFFFF,t_70,g_se,x_16)

In special cases, when the attributes of a child and a parent are renamed with the same name, you must add the modifier super. Only through super. Property to call
In special cases, when the method of a child and a parent class have the same name, the modifier super. must be added if you want to use the method of the parent class. Only through super. Method Call
In this case, super. You cannot omit not to write.

[3] super modifier constructor:
In fact, the first line of the constructor we usually write has: super() --> effect: call the empty constructor of the parent class, but we usually omit it
(The first line of all constructors has super () by default, but once your constructor shows a parent constructor called with super, this super () will not be assigned to you by default. If the parent constructor is not called as shown in the constructor, then the first line has super(), which can be omitted from writing

If the call super parent constructor is already shown in the constructor, there is no default allocated super() in its first line; Yes

In a constructor, there can only be one super call parent constructor and this call subclass constructor, and they cannot coexist:
Because the super modifier is placed on the first line, the this modifier is also placed on the first line:

Correct the two choices:

[4] In the future, code constructors can be generated directly using the shortcut keys provided by IDEA: alt+insert

Benefits of inheritance: Enhance code reuse
The content defined by the parent class, which can be used directly by the subclass, does not have to be redefined over and over again in code

Points to note:
The parent private ly modifies the content, and the subclasses actually inherit it, simply because the encapsulated nature prevents direct calls, but provides a way to make indirect calls, which can be called indirectly.
Summary:
(1) Inheritance:

  • Parent/Base/Superclass
  • Subclass/Derived Class
  • Subclass inherits a subclass extends parent whose parent must inherit within a reasonable range

(2) Benefits of inheritance:

  • Enhanced code reuse, parent-defined content, subclasses can be taken directly to use, without repeatedly defining on the code
  • Easy code extension
  • For future use of polymorphism. It is a prerequisite for polymorphism.

(3) The parent private ly modifies the content, and the child inherits it.
(4) A parent class can have multiple subclasses.
(5) A subclass can have only one direct parent.
But it can be inherited indirectly from other classes.
(6) Inheritance is transitive:
Student ->Inherited from Person ->Inherited from Object
The Object class is the root parent of all classes.
All classes inherit directly or indirectly from Object.

polymorphic

[1] Polymorphism has nothing to do with attributes. Polymorphism refers to the polymorphism of methods, not attributes.
[2] Case substitution:

public class Animal {//Parent: Animals:
    public void shout(){
        System.out.println("I'm a small animal. I can call.");
    }
}

Dogs:

public class Dog extends Animal{
    //Cry:
    public void shout(){
        System.out.println("I'm a puppy, I can bark");
    }
    public void guard(){
        System.out.println("I'm a puppy. I can watch the nursing home and protect my little owner.");
    }
}

Pigs:*

public class Pig extends Animal{
    public void shout(){
        System.out.println("I'm a piglet, I call a little*");
    }
    public void eat(){
        System.out.println("I'm a piglet. I love to eat. *");
    }
}

Girls:

public class Girl {
    //Playing with a dog:
    /*public void play(Dog dog){
        dog.shout();
    }*/
    //Playing with pigs*
    /*public void play(Pig pig){
        pig.shout();
    }*/
    //Playing with small animals:
    public void play(Animal an){
        an.shout();
    }
}

Test class:

public class Test {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
    	//Specific little girl: --"Girl's object
        Girl girl = new Girl();
        //Specific Dog---"The object of the dog:
        //Dog dog = new Dog();
        //The little girl plays with the dog:
        //girl.play(dog); // I'm a puppy, I can bark
        
        //Specific Pig: --*The object of the pigs*
        //Pig pig = new Pig();
        //The little girl plays with the pigs*
        //girl.play(pig); // I'm a piglet, I call a little*
        //- The above two methods are not flexible enough ---//
        
        //Specific animals: --) Animal objects:
        //Dog dog = new Dog();
        Pig pig = new Pig();
        Animal an = pig;   //Animal an = new Pig();
        girl.play(an);  //I'm a piglet, I call a little*
    }
}

[3] Summary:
(1) First there is a parent class, then a child class:-- "Inherit a child class, then extract a parent class----" Generalization
(2) What is polymorphism:
Polymorphism is a variety of states: the same behavior, different subclasses show different forms.
Polymorphism refers to the same method call, which then behaves differently depending on the object.

(3) Benefits of polymorphism:
To improve the scalability of the code, it conforms to the object-oriented design principle: the open and close principle.
Open-Close Principle: It means that expansion is open and modification is closed.
Note: Polymorphism improves scalability, but scalability is not optimal. -- reflex
(4) Elements of polymorphism:
_1, Inheritance: Cat extends Animal, Pig extends Animal, Dog extends Animal
_2, Override: Subclass overrides parent class's method shout()
_3, parent references point to subclass objects:

Pig p = new Pig();
Animal an = p;
Combine the above code into one sentence: Animal an = new Pig();
=Left: Compile-time type
=Right: Type of runtime

Downward Transition, Upward Transition



To access the eat() method and the weight property:

public class Demo {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        Pig p = new Pig();
        Animal an = p;//Transition: Upward Transition
        an.shout(); //I'm a piglet. I'm Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm-Hmm*
        //Code to join the transition:
        //Convert Animal to Pig type: 
        Pig pig = (Pig)an ;//Transition: Downward Transition
        pig.eat(); //I'm a piglet. I love to eat. *
        pig.age = 10;
        pig.weight = 60.8;
    }
}

Corresponding memory:

abstract class

[1] Relationship between abstract classes and abstract methods: 0-n abstract methods can be defined in an abstract class.
[2] Abstract class actions:
The purpose of defining abstract methods in abstract classes is to provide a common template for subclasses, which can be developed on the basis of templates, rewriting the abstract methods of the parent class, and then expanding the contents of the subclass itself. Abstract class design avoids the arbitrariness of subclass design, through which the design of subclasses becomes more stringent and somewhat restricted.
Make subclasses more generic.
[3] Code:

//4. If there is a method in a class that is abstract, then the class will also become an abstract class.
//5. There may be 0-n abstract methods in an abstract class
public abstract class Person {
    //1. In a class, there will be a class of methods, the subclass is very satisfied with this method, no need to override, use directly
    public void eat(){
        System.out.println("Panic without hunger at a meal");
    }
    //2. In a class, there will be a class of methods, and subclasses will never be satisfied with this method and will override it.
    //3. If the body of a method is removed and then abstracted, the method becomes an abstract method.
    public abstract void say();
    public abstract void sleep();
}
//6. Abstract classes can be inherited by other classes:
//7. A class inherits an abstract class, then it can become an abstract class
//8. Normal subclasses do not have abstract modifiers and will generally cause subclasses to override abstract methods in the parent class
//9. Subclasses inherit abstract classes and must override all abstract methods
//10. A subclass can also become an abstract class if it does not override all of its parent's Abstract methods.
class Student extends Person{
    @Override
    public void say() {
        System.out.println("I am from the Northeast and I like to speak Northeast.");
    }
    @Override
    public void sleep() {
        System.out.println("Northeast people like sleeping.");
    }
}
class Demo{
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //11. Objects that create abstract classes: -->Abstract classes cannot create objects
        //Person p = new Person();
        //12. Create subclass objects:
        Student s = new Student();
        s.sleep();
        s.say();
        
        //13. Writing polymorphic: parent references only want subclass objects:
        Person p  = new Student();
        p.say();
        p.sleep();
    }
}

Interface

[1] Interface declaration format:

[Access modifier] Interface interface name [extends parent interface 1, parent interface 2...] {
_constant definition;
_method definition;
}

[2] Code:

package com.msb.test04;
/**
 * 1.Classes are classes and interfaces are interfaces. They are concepts at the same level.
 * 2.There is no constructor in the interface
 * 3.How an interface declares:
 * 4.In JDK1. Prior to 8, there were only two parts in the interface:
 * (1)Constant: fixed modifier: public static final
 * (2)Abstract method: fixed modifier: public abstract
 * Note: Modifiers can be omitted from writing, IDE will help you to complete automatically, but beginners suggest writing to prevent forgetting.
 */
public interface TestInterface01 {
    //Constant:
    /*public static final*/ int NUM = 10;
    //Abstract methods:
    /*public abstract*/ void a();
    /*public abstract*/ void b(int num);
    /*public abstract*/ int c(String name);
}
interface TestInterface02{
    void e();
    void f();
}
/*
5.What is the relationship between a class and an interface? Implement a relationship class to implement an interface:
6.Once an interface is implemented, the implementation class overrides all abstract methods in the interface:
7.If you don't override all abstract methods, this class can become an abstract class.
8.java java has more implementations than inheritance alone
 A class inherits other classes and can only directly inherit a parent class
 But if you implement a class that implements an interface, you can implement multiple interfaces
9.Writing: Inherit before implementation: extends Person implements TestInterface01,TestInterface02
 */
class Student extends Person implements TestInterface01,TestInterface02 {
    @Override
    public void a() {
        System.out.println("---1");
    }
    @Override
    public void b(int num) {
        System.out.println("---2");
    }
    @Override
    public int c(String name) {
        return 100;
    }
    @Override
    public void e() {
        System.out.println("---3");
    }
    @Override
    public void f() {
        System.out.println("---4");
    }
}
class Test{
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //10. Interfaces cannot create objects:
        //TestInterface02 t = new TestInterface02();
        TestInterface02 t = new Student();//Interface Points to Implementation Class---"Polymorphism
        //11. How is the common access in an interface?
        System.out.println(TestInterface01.NUM);
        System.out.println(Student.NUM);
        Student s = new Student();
        System.out.println(s.NUM);
        TestInterface01 t2 = new Student();
        System.out.println(t2.NUM);
    }
}

What is the function of the interface?
_Defines rules, just where are they different from abstract classes? It is an interface, not a class.
Once the interface has defined the rules, the implementation class is responsible for the implementation.

[4]
Inheritance: Subclass inheritance to parent
_Implementation: Implementing class-to-class interfaces

[5] Application of polymorphism:
(1) The parent class acts as a parameter of the method, passing in objects of a specific subclass
(2) The parent class acts as the return value of the method and returns the object of the specific subclass.
(3) Interface as a parameter of a method, passing in the object of a specific implementation class
(4) The interface acts as the return value of the method, returning the object of the specific implementation class

[6] Differences between interfaces and abstract classes:



 
In JDK1. After 8, add non-abstract methods

In JDK1. Prior to 8, there were only two parts in the interface:
(1) Constant: fixed modifier: public static final
(2) Abstract method: fixed modifier: public abstract

In JDK1. After 8, add non-abstract methods:
(1) Non-abstract methods decorated by public default:
Note that the 1:default modifier must be added or an error will occur
Note 2: If you want to override a non-abstract method in an interface in an implementation class, the default modifier must not be added or an error will occur.

public interface TestInterface {
    //Constant:
    public static final int NUM= 10;
    //Abstract methods:
    public abstract void a();
    //Non-abstract methods decorated with public default:
    public default void b(){
        System.out.println("-------TestInterface---b()-----");
    }
}
class Test implements TestInterface{
    public void c(){
        //Use the b method in the following interface:
        b();//Yes?
        //super.b(); May not
        TestInterface.super.b();//Yes?
    }
    @Override
    public void a() {
        System.out.println("Rewritten a Method");
    }
    @Override
    public void b() {
    }
}

(2) Static method:
Note that 1:static cannot be omitted from not writing
Note 2: Static methods cannot be overridden

public interface TestInterface2 {
    //Constant:
    public static final int NUM = 10;
    //Abstract methods:
    public abstract  void a();
    //public default is a non-abstract method;
    public default void b(){
        System.out.println("-----TestInterface2---b");
    }
    //Static method:
    public static void c(){
        System.out.println("TestInterface2 Static methods in");
    }
}
class Demo implements TestInterface2{
    @Override
    public void a() {
        System.out.println("Rewritten a Method");
    }
    public static void c(){
        System.out.println("Demo Static methods in");
    }
}
class A {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        Demo d = new Demo();
        d.c(); //Static methods in Demo
        Demo.c(); //Static methods in Demo
        TestInterface2.c();//Static methods in TestInterface2
    }
}

Question: Why should I add non-abstract methods to the interface???
If only abstract methods can be defined in an interface, then if I modify the contents of the interface, the impact on the implementation classes will be too large, and all the implementation classes will be affected.
Now add a non-abstract method to the interface without affecting the implementation class. Call it whenever you want.

this keyword

[1] The process of creating objects:
(1) When a class is first encountered, it is loaded only once.
(2) Create objects to open up space in the heap
(3) Initialize the object, and attribute assignments are the default initial values.
(4) The new keyword calls the constructor, executes the construction method, and reassigns the attribute in the constructor


You can see from the above effect that this refers to the current object:
From memory:

this keyword usage:

this can modify attributes:

Summary: The proximity principle occurs when attribute names and parameters are renamed, or when attribute names and local variables are renamed, so if I use variable names directly, I refer to the near parameter or local variable. If I want to represent attributes, add this before. Modification

If there is no duplicate name problem, you can actually omit this if you access the property.

public class Person {
    //attribute
    int age;
    String name;
    double height;
    //Empty constructor
    public Person(){
    }
    //Parametric constructor
    public Person(int age,String name,double height){
        this.age = age;
        this.name = name;
        this.height = height;
    }
    //Method:
    public void eat(){
        int age = 10;
        System.out.println(age);//Proximity principle, age refers to the age of a local variable in age--.
        System.out.println(this.age);//This refers to the age of the attribute
        System.out.println("I like to eat");
    }
}

this modification method:

Summary: In the same class, methods can call each other, this. You can omit not writing.

public class Person {
    //attribute
    int age;
    String name;
    double height;
    //Empty constructor
    public Person(){
    }
    //Parametric constructor
    public Person(int age,String name,double height){
        this.age = age;
        this.name = name;
        this.height = height;
    }
    //Method:
    /*public void eat(){
        int age = 10;
        System.out.println(age);//Proximity principle, age refers to the age of a local variable in age--.
        System.out.println(this.age);//This refers to the age of the attribute
        System.out.println("I like to eat ";
    }*/
    public void play(){
        /*this.*/eat();
        System.out.println("smoking");
        System.out.println("drink");
    }
    public void eat(){
        System.out.println(/*this.*/age);
        System.out.println("Ironing");
    }
}

this can modify the constructor:

Summary: Constructors in the same class can call each other with this, note that this modifier must be placed on the first line

public class Person {
    //attribute
    int age;
    String name;
    double height;
    //Empty constructor
    public Person(){
    }
    //Parametric constructor
    public Person(int age,String name,double height){
        this(age,name);
        this.height = height;
    }
    public Person(int age,String name){
        this(age);
        this.name = name;
    }
    public Person(int age){
        this.age = age;
    }
    //Method:
    /*public void eat(){
        int age = 10;
        System.out.println(age);//Proximity principle, age refers to the age of a local variable in age--.
        System.out.println(this.age);//This refers to the age of the attribute
        System.out.println("I like to eat ";
    }*/
    public void play(){
        /*this.*/eat();
        System.out.println("Surf the Internet");
        System.out.println("Take a shower");
    }
    public void eat(){
        System.out.println(/*this.*/age);
        System.out.println("Having dinner");
    }
}

static keyword

Statics can be modified: attributes, methods, code blocks, internal classes.

static modifies attributes;

General recommendation: you can access it by class name. Attribute name access

public class MsbStudent {
    //Attributes:
    String name;
    static String age;
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        MsbStudent.age = "Girlfriend's 70th birthday today!";  //Access mode 1
        //Create Student Objects:
        MsbStudent s1 = new MsbStudent();
        s1.name = "Zhang San";
        //s1.age = Today's birthday; // Access Mode 2
        System.out.println(s1.age);   //Girlfriend's 70th birthday today!
    }
}

static Modification Method

Summary of static modifiers:
(1) Load classes together into static fields in the method area when they are loaded
(2) prior to object existence
(3) Access method: Object name, Attribute name, Class name, Attribute name (recommended)

public class Demo {
    int id;
    static int sid;
    public void a(){
        System.out.println(id);
        System.out.println(sid);
        System.out.println("------a");
    }
    //1.static and public are modifiers, side by side without precedence. Write whomever comes first, then whomever goes
    static public void b(){
        //System.out.println(this.id);//4. This keyword cannot be used in static methods
        //a();//3. Non-static methods cannot be accessed in static methods
        //System.out.println(id);//2. Non-static properties cannot be accessed in static methods
        System.out.println(sid);
        System.out.println("------b");
    }
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //5. Non-static methods can use object names. Method name to call
        Demo demo = new Demo();
        demo.a();
        //6. Static methods can use object names. A method name can also be called with a class name. Method name (recommended)
        Demo.b();
        demo.b();
       
    }
}

final keyword

Modifier variable

public class Test {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //Case 1:
        //final modifies a variable whose value cannot be changed, and it becomes a character constant that conveys the common rule: capitalization of names
        final int A = 10;//final modifies basic data types
        //A = 20; Error: Value cannot be modified
        //Case 2:
        final Dog d = new Dog();//final modifies the reference data type so that the address value cannot be changed
        //D = new Dog(); --> Address value cannot be changed
        //The properties inside the d object can still be changed:
        d.age = 10;
        d.weight = 13.7;
        //Case 3:
        final Dog d2 = new Dog();
        a(d2);
        //Case 4:
        b(d2);
    }
    public static void a(Dog d){
        d = new Dog();
    }
    public static void b(final Dog d){//d is modified by final, pointing cannot be changed
        //d = new Dog(); --) Report errors
    }
}

Modification Method

final modifier, then this method cannot be overridden by subclasses of this class:

Modifier class

final modifier class, representing no subclass, that cannot be inherited:
Once a class is finalized, there is no need to modify the methods inside (finals can be omitted from writing)

[4] Case: Math class provided by JDK: See Source Discovery:
(1) When using Math classes, there is no need to import them, but they can be used directly:

(2) Math class has no subclasses and cannot be inherited by other classes

(3) The attributes inside are all modified by final, and the methods are also modified by final, except that they are omitted and not written.
Reason: There is no need to override subclasses.

(4) The outside world may not create objects:
Math m = new Math();

(5) Discover that all attributes in the Math class are modified by static
Instead of creating an object to invoke, you can only invoke it through the class name. Attribute name Class name. Method name to call


abnormal

[1] Under what circumstances does the code behind try-catch not execute?
(1) throw throws an exception
(2) There is no normal exception capture in catch
(3) encounter return in try

[2] How can the code behind try-catch have to be executed?
_As long as the code that must be executed is put into finally, it will execute anyway.

[3] Order of return and finality execution?
_Execute finally first and return last

[4] What code will be put in finally?
_Close database resources, IO stream resources and socket resources.

[5] There's a sentence about code that's so bad that it doesn't execute in finally!
_System.exit(0);// Terminate current virtual machine execution

Code:

public class Test3 {
    public static void main(String[] args) {
        //Implement a function: Keyboard input two numbers, seeking quotation:
        try{
            Scanner sc = new Scanner(System.in);
            System.out.println("Please enter the first number:");
            int num1 = sc.nextInt();
            System.out.println("Please enter the second number:");
            int num2 = sc.nextInt();
            System.out.println("Quotient:"+num1/num2);
            System.exit(0);//Terminate current virtual machine execution
            return;
        }catch(ArithmeticException ex){
            //throw ex;
        }finally {
            System.out.println("----Thank you for using Calculator 111");
        }
    }
}

Exception Classification


Note: Grammar errors, logic errors in the program do not belong to the above Error, Exception

[2] Runtime exceptions:

public class Test5 {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //Runtime exceptions:
        int[] arr = {1,2,3};
        System.out.println(arr.length);
        /*int[] arr2 = null;
        System.out.println(arr2.length);*/
        System.out.println(arr[10]);
    }
}

[3] Examine abnormalities:
Processing 1:try-catch nested try-catch

public class Test6 {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //Check for exceptions:
        try {
            try {
                Class.forName("com.msb.test01.Test").newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}

Processing Mode 2: Multiple Catches

public class Test6 {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) {
        //Check for exceptions:
        try {
            Class.forName("com.msb.test01.Test").newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

Processing 3:throws

public class Test6 {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //Check for exceptions:
        Class.forName("com.msb.test01.Test").newInstance();
    }
}

The difference between throw and throws

public class Test7 {
    //This is the main method, which is the entry to the program:
    public static void main(String[] args) throws Exception {
        //Implement a function: divide two numbers, when the divider is 0, the program has an exception.
        /*try {
            devide();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        devide();
    }
    public static void devide() throws Exception {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter the first number:");
        int num1 = sc.nextInt();
        System.out.println("Please enter the second number:");
        int num2 = sc.nextInt();
        if(num2 == 0 ){//Divide by 0, creating an exception.
            //Make runtime exceptions:
            /*throw new RuntimeException();*/
            //Make check exception:
            /*try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }*/
            throw new Exception();
        }else{
            System.out.println("Quotient:"+num1/num2);
        }
    }
}

Summary:
The difference between throw and throws:
(1) Different locations:
_throw: Inside the method
_throws: Signature of method, declaration of method

(2) Contents are different:
_throw+exception object (check for exceptions, run-time exceptions)
_throws+types of anomalies (can be multiple types, used, stitched)

(3) Different functions:
_throw: The source of an anomaly, creating an anomaly.
_throws: At the declaration of a method, tell the caller of the method that these exceptions I declare may occur in this method. The caller then handles the exception:
_Either handle it yourself or continue throwing exceptions outward

Custom Exception

Custom exceptions can inherit: Runtime exceptions

public class MyException extends RuntimeException {
    
    static final long serialVersionUID = -70348971907L;
    
    public MyException(){
    }
    public MyException(String msg){
        super(msg);
    }
}

You can also inherit check exceptions:

public class MyException extends Exception {
    static final long serialVersionUID = -70348971907L;
    public MyException(){
    }
    public MyException(String msg){
        super(msg);
    }
}

If runtime exceptions are inherited, no extra handling is required when using
If you inherit check exceptions, try-catch capture or throws are required when using


Common Classes

Keywords: Java Back-end

Added by joshmaker on Mon, 03 Jan 2022 22:13:11 +0200