[Java Basics] Study Notes 4 - Enumeration classes, annotations and exceptions

enum class

The definition of enumeration class is more complicated

Explain based on the code below

  1. Enumeration constants must be at the top of the enumeration class. They represent the constants we need to use.
  2. Define private properties that will become parameters in enumeration constants
  3. Define the constructor. The format of the constructor corresponds to the format of the enumeration constant, and assign values ​​to private properties one by one.
  4. Define the getter of the private property so that the outside world can obtain the parameter value in the enumeration constant
package chapter3;

public class EnumClass {
    
    
    public static void main(String[] args) {
    
    
        Persons[] persons = Persons.values();
        for (Persons person : persons) {
    
    
            StringBuilder sb = new StringBuilder();
            sb.append(person.getAge());
            sb.append(person.getName());
            sb.append(person.name());
            System.out.println(sb.toString());
        }
    }
}

enum Persons {
    
    
    JACK("jack", 12),  // 枚举常量 JACK,名称为 "jack",年龄为 12
    TOM("tom", 13),   // 枚举常量 TOM,名称为 "tom",年龄为 13
    WHITE("white", 41),  // 枚举常量 WHITE,名称为 "white",年龄为 41
    ALIEN("undefined");  // 枚举常量 ALIEN,名称为 "undefined",使用默认年龄 999

    private final String name;  // 枚举常量的名称
    private final int age;  // 枚举常量的年龄

    // 枚举常量的构造方法,接受名称和年龄
    Persons(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    // 枚举常量的构造方法,只接受名称,年龄使用默认值 999
    Persons(String name) {
    
    
        this.name = name;
        this.age = 999;
    }

    // 获取枚举常量的名称
    public String getName() {
    
    
        return name;
    }

    // 获取枚举常量的年龄
    public int getAge() {
    
    
        return age;
    }
}

Or, use the simplest method directly. All enumeration constants themselves are string constants.
They do not require any parameters and only need to be taken out when they are used again name().

public class EnumClass {
    
    
    public static void main(String[] args) {
    
    
        GENDER boy = GENDER.BOY;
        GENDER girl = GENDER.GIRL;
        System.out.println(boy.name());
    }
}

enum GENDER {
    
    
    BOY, GIRL;
}

Because the enumeration class enum implicitly inherits Enum by default, you can no longer use extends, but you can still implement the interface!

The enumeration class mounts multiple interfaces and then implements them, so that it can be directly called by the outside world.

package chapter3;

public class EnumInterfaceClass {
    
    
    public static void main(String[] args) {
    
    
        // 直接通过枚举常量调用对应接口方法
        BB.ASD.say();
    }
}

// 接口
interface B {
    
    
    void say();
}

enum BB implements B {
    
    

    ASD("asd"), QWE("qwe");

    private final String msg;

    BB(String msg) {
    
    
        this.msg = msg;
    }

    // 实现对应的方法
    @Override
    public void say() {
    
    
        System.out.println(msg);
    }
}

annotation

Three common annotations:

  • @Overrideoverride annotation
  • @DeprecatedThe representation method is deprecated
  • @SuppressWarningssuppress compiler warnings

@Override

Can only modify methods

It can only be specified as a method that overrides the parent class. If the parent class does not have this method, an error will be reported.

@TargetIt is an annotation that modifies annotations, also called meta-annotations.


@Deprecated

All type members can be annotated

Indicates that the type is obsolete and is used for switching between old and new versions.


@SuppressWarnings

suppress compiler warnings

The range of suppression depends on where you place the annotation.

You can specify which aspects of annotations to suppress. You can check the corresponding suppressed names online.

@SuppressWarnings({
    
    "unchecked"})
public void asd(){
    
    }

Four Meta-Annotations

@Retention: Used to specify the retention policy of the annotated annotation. The annotation retention policy determines whether the annotation is visible at compile time, class loading time, or run time.
It accepts one parameter, the optional values ​​are:

  • RetentionPolicy.SOURCE: The annotation is only retained in the source code and will not be included in the compiled file after compilation.
  • RetentionPolicy.CLASS: The annotation is retained in the compiled bytecode file, but will not be loaded into the virtual machine and is not visible at runtime.
  • RetentionPolicy.RUNTIME: Annotations are retained in the compiled bytecode file and loaded into the virtual machine, and can be obtained through the reflection mechanism at runtime.

@Target: Used to specify which elements the annotated annotation can be applied to. Annotations can be applied to different elements such as classes, methods, fields, etc. @Target is used to limit the scope of use of annotations.
@Target accepts a parameter ElementType[], indicating the element type to which the annotation can be applied.

@Documented: Used to specify whether the annotated annotation is included in the Java document. If an annotation is annotated with this annotation d, the annotation will be included in the Java document when it is generated.

@Inherited: Used to specify whether the annotated annotation can be inherited. When a class is inherited, whether to inherit the annotations on the parent class.


abnormal

Exceptions can be divided into two categories:

  1. Error: Serious problems that cannot be solved by the JVM, such as internal system errors or resource exhaustion.
  2. Exception: General error, such as null pointer exception; it can be divided into two major categories:
    • Runtime exceptions: Exceptions that do not require forced handling are generally logical errors during programming.
    • Compile-time exceptions: Exceptions that the compiler requires to be handled

runtime exception

Common runtime exceptions:

  1. NullPointerException (null pointer exception): thrown when code attempts to use a method of a null object or access a property of a null object.
  2. ArrayIndexOutOfBoundsException (array out of bounds exception): thrown when trying to access an index that does not exist in the array.
  3. ClassCastException (class conversion exception): thrown when trying to cast an object to an incompatible type.
  4. NumberFormatException (number format exception): thrown when the string cannot be converted to a numeric type. For example, when using Integer.parseInt, the incoming string is not in a legal numeric format.
  5. ArithmeticException: An error occurs when performing an arithmetic operation, such as dividing by zero or dividing by zero during a modulo operation.
  6. IllegalArgumentException (illegal parameter exception): thrown when the parameters passed to the method are illegal or invalid, such as passing an empty object or disallowed parameter value.
  7. IllegalStateException: Thrown when an object is in an impermissible state, such as when a method or operation is called at an incorrect time.
  8. IndexOutOfBoundsException (index out of bounds exception): thrown when accessing a non-existing index in a collection (such as a list or string).
  9. ConcurrentModificationException (Concurrent Modification Exception): Thrown when the collection is iterated and modified in an impermissible way (such as modifying the collection).
  10. UnsupportedOperationException: Thrown when an unsupported method or operation is called, usually because the object does not support a specific operation.

catch exception

The simplest try catch code block to catch exceptions

Subclass exceptions are written in front, and parent class exceptions are written in the back.

finally means code that will be executed no matter what

package chapter4;

public class Exp1 {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            String str = "123";
            int num = Integer.parseInt(str);
            System.out.println(num);
        } catch (NumberFormatException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            System.out.println("我一直会被执行");
        }
    }
}

Throw an exception

We can just mess it up and not actively handle the exception, but let the subclass handle it.

At this time, you can use throw to throw an exception. The thrown exception can be the parent class of the current exception;
if you want to save trouble, you can directlythrow Exception

package chapter4;

public class Exp2 {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            int num = new Exp2().getNum("asd");
            System.out.println(num);
        } catch (NumberFormatException e) {
    
    
            e.printStackTrace();
        }
    }

    public int getNum(String str) throws NumberFormatException {
    
    
        return Integer.parseInt(str);
    }
}

Compile-time exceptions must be handled or thrown; run-time exceptions are generally thrown directly;

There is no need to throw an exception if you have already handled it


Custom exception

package chapter4;

import java.util.Scanner;

public class Exp3 {
    
    
    public static void main(String[] args) {
    
    
        int age = 100;
        if (age < 100) throw new CustomException("你的数字不对");
    }
}

class CustomException extends RuntimeException {
    
    
    public CustomException(String message) {
    
    
        super(message);
    }
}

Guess you like

Origin blog.csdn.net/delete_you/article/details/132698142