01. java object-oriented-enumerations and annotations

java object-oriented-enumerations and annotations

1. Enumeration class introduction

1. Description

? Let us first look at a piece of code to understand why we need an enumeration class

public class Enumeration01 {<!-- -->
    public static void main(String[] args) {<!-- -->
        Season season = new Season("spring", "warmth");
        Season winter = new Season("winter", "cold");
        Season summer = new Season("summer", "hot");
        Season autumn = new Season("autumn", "cool");
        //1. Because for seasons, its objects (specific values) are fixed four, and there will not be more. The problem is
        //2. There is a problem with your idea of designing a class. It only has four corresponding objects. The class we designed can be created at will.
        //3. Lead to enumeration =======> Enumeration class [enum: one by one, enumeration: example, enumerate specific objects one by one]
        //4. This is the so-called enumeration class
        Season other = new Season("黄天", "~~~~");

    }
}
class Season {<!-- -->
    private String name;
    private String desc;

    public Season(String name, String desc) {<!-- -->
        this.name = name;
        this.desc = desc;
    }

    public String getName() {<!-- -->
        return name;
    }

    public void setName(String name) {<!-- -->
        this.name = name;
    }

    public String getDesc() {<!-- -->
        return desc;
    }

    public void setDesc(String desc) {<!-- -->
        this.desc = desc;
    }
}
2. Creating a Season object has the following characteristics
  1. The value of season is a limited number of values (spring, summer, autumn, winter)

    1. Read only, no need to modify

2. Enumeration class

1. Basic introduction
  1. Enumeration corresponds to English (enumeration, abbreviated enum)

    1. An enumeration is a collection of constants
    2. It can be understood this way: an enumeration belongs to a special class, which only contains a limited and specific object.
2. Two implementation methods of enumeration
  1. Custom implementation of enumeration
  2. Implement enumeration using enum keyword

3. Custom enumeration class

1. Description
  1. There is no need to provide a SetXxx method because enumeration objects are usually read-only
  2. Use final + static to jointly modify enumeration objects/properties to achieve underlying optimization
  3. Enumeration object names usually use all uppercase, constant naming convention
  4. Enumeration objects are more desirable and can have multiple properties
2. Implementation steps
  1. Constructor privatization
  2. Create a set of objects within this class
  3. Expose the object to the outside world (by adding the public final static modifier to the object)
  4. You can provide a get method, but do not provide a set
public class Enumeration02 {<!-- -->
    public static void main(String[] args) {<!-- -->
        System.out.println(Season02.AUTUMN);
        System.out.println(Season02.SPRING);

    }
}

//1. Demonstrate custom enumeration implementation
class Season02 {<!-- -->
    private String name;
    private String desc;
    //4. Four objects are defined, fixed
    //5. Optimize and add final modification
    public final static Season02 SPRING = new Season02("spring", "warmth");
    public final static Season02 WINTER = new Season02("winter", "cold");
    public final static Season02 SUMMER = new Season02("summer", "hot");
    public final static Season02 AUTUMN = new Season02("Autumn", "Cool");
    //1. Privatize the constructor to prevent direct new
    //2. Remove the set method to prevent attribute modification
    //3. Create objects within Season02
    private Season02(String name, String desc) {<!-- -->
        this.name = name;
        this.desc = desc;
    }

    public String getName() {<!-- -->
        return name;
    }



    public String getDesc() {<!-- -->
        return desc;
    }

    @Override
    public String toString() {<!-- -->
        return "Season02{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

4. The enum keyword implements enumeration

1. Description

? Use enum to implement the previous enumeration case and see the difference between viewing and customizing

public class Enumeration03 {<!-- -->
    public static void main(String[] args) {<!-- -->
        System.out.println(Season03.SPRING + " " + Season03.WINTER);
    }
}
// Demonstrates the use of enum to implement enumeration
enum Season03 {<!-- -->

// public final static Season02 SPRING = new Season02("spring", "warmth");
// public final static Season02 WINTER = new Season02("winter", "cold");
// public final static Season02 SUMMER = new Season02("summer", "hot");
// public final static Season02 AUTUMN = new Season02("Autumn", "Cool");

    //If enum is used to implement enumeration
    //1. Use the keyword enum instead of class
    //2. public final static Season02 SPRING = new Season02("spring", "warmth"); Use directly
    //3. SPRING("spring","warmth"); --- constant name (actual parameter list);
    SPRING("spring","warm"), WINTER("winter","cold");
    private String name;
    private String desc;

    private Season03(String name, String desc) {<!-- -->
        this.name = name;
        this.desc = desc;
    }

    public String getName() {<!-- -->
        return name;
    }



    public String getDesc() {<!-- -->
        return desc;
    }

    @Override
    public String toString() {<!-- -->
        return "Season02{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

2. Things to note when implementing enumeration using the enum keyword
  1. When we use the enum keyword to develop an enumeration class, the Enum class will be inherited by default (proven using the javap tool)
  2. Traditional public final static Season02 SPRING = new Season02(“spring”, “warmth”), here you must know which constructor it calls.
  3. If a parameterless constructor is used to create an enumeration object, the parameter list and parentheses can be omitted.
  4. When there are multiple enumeration objects, use , and each interval ends with a semicolon.
  5. The enumeration object must be placed at the beginning of the line of the enumeration class

5. Application examples of enum common methods

  1. toString: The Enum class has been rewritten to return the current object name. Subclasses can override this method to return the object’s attribute information.
  2. name: Returns the current object name (constant name), which cannot be overridden in subclasses
  3. ordinal: Returns the position number of the current object, starting from 0 by default
  4. values: Returns all constants in the current enumeration
  5. valuesOf: Convert a string into an enumeration object. The string must be an existing constant, otherwise an exception will be reported!
  6. compareTo: Compare two enumeration constants, what is compared is the position number!
public class EnumMethod {<!-- -->
    public static void main(String[] args) {<!-- -->
        //Use Season03 enumeration class to demonstrate various methods
        Season03 autumn = Season03.AUTUMN;
        //Output the name of the enumeration object
        System.out.println(autumn.name());
        //ordinal() outputs the order/number of the enumeration object: numbering starts from 0
        //AUTUMN enumeration object is the fourth, so output 3
        System.out.println(autumn.ordinal());
        //It can be seen from decompilation that the values method returns Season03[]
        // Contains all enumeration objects defined
        Season03[] values = Season03.values();
        System.out.println("===Traverse and remove enumeration objects====");
        for (Season03 season03: values) {<!-- -->//Enhanced for loop
            System.out.println(season03);
        }

        //valuesOf: Convert the string into an enumeration object. The string must be an existing constant, otherwise an exception will be reported!
        //Execution process: Search in the Season03 enumeration object based on the "AUTUMN" you entered
        //If found, return, if not found, report an error
        Season03 season03 = Season03.valueOf("AUTUMN");
        
        //compareTo: Compare two enumeration constants, what is compared is the position number!
        System.out.println(Season03.AUTUMN.compareTo(Season03.SUMMER));

// //Enhanced for loop case
// int[] nums = {1, 2, 3};
// System.out.println("==========");
// for (int i = 0; i < nums.length; i + + ) {<!-- -->
// System.out.println(nums[i]);
// }
// System.out.println("=============");
// for (int i: nums) {<!-- -->
// System.out.println(i);
// }
    }
}

6.enum exercises

  1. Declare the Week enumeration class, which contains the definitions of Monday to Sunday: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
  2. Use values to return all enumeration arrays, traverse, and output
public class EnumExercise02 {<!-- -->
    public static void main(String[] args) {<!-- -->
        //Get all enumeration objects
        Week[] weeks = Week.values();
        for (Week week : weeks) {<!-- -->
            System.out.println(week);
        }
    }
}
enum Week {<!-- -->
    MONDAY("Monday"), TUESDAY("Tuesday"), WEDNESDAY("Wednesday"),
    THURSDAY("Thursday"),FRIDAY("Friday"), SATURDAY("Saturday"), SUNDAY("Sunday");
    private String name;

    Week(String name) {<!-- -->
        this.name = name;
    }

    @Override
    public String toString() {<!-- -->
        return name;
    }
}

7. enum implements the interface

  1. After using the enum keyword, you can no longer inherit from other classes, because enum will implicitly inherit Enum, and Java has a single inheritance mechanism.
  2. Enumeration classes, like ordinary classes, can implement interfaces in the following form.
    enum class name implements interface 1, interface 2 {}
public class EnumDetail {<!-- -->
    public static void main(String[] args) {<!-- -->
        Music.CLSSICMUISC.playing();
    }
}
class A {<!-- -->
}
//1. Cannot inherit classes
//enum Season03 implements A {<!-- -->
//}
interface IPlaying {<!-- -->
    public void playing();
}
enum Music implements IPlaying {<!-- -->
    CLSSICMUISC;
    @Override
    public void playing() {<!-- -->
        System.out.println("Play music....");
    }
}

8. Annotations

1. Understanding annotations
  1. Annotation, also known as metadata, is used to modify and interpret data information such as packages, classes, methods, properties, constructors, and local variables.

  2. Like comments, annotations do not affect program logic, but they can be compiled or run and are equivalent to supplementary information embedded in the code.

  3. In JavaSE, the purpose of using annotations is relatively simple, such as marking obsolete functions, ignoring warnings, etc. Annotations play a more important role in Java EE, such as being used to configure any aspect of the application, replacing the cumbersome code and XML configuration left in the old version of Java EE.

2. Basic Annotation introduction

? When using an Annotation, add the @ symbol in front of it and use the Annotation as a modifier. Used to modify the program elements it supports

? Three basic Annotations:

  1. @Override: To limit a method, it is to override the parent class method. This annotation can only be used for methods.
  2. @Deprecated: used to indicate that a program element (class, method, etc.) is obsolete
  3. @SuppressWarnings: Suppress compiler warnings
3. Basic Annotation application cases
1. Case of @Override annotation
public class Override_ {<!-- -->
    public static void main(String[] args) {<!-- -->
        
    }
}
class Father{<!-- -->//Father class
    public void fly(){<!-- -->
        System.out.println("Father fly...");
    }
    public void say(){<!-- -->}
}
class Son extends Father {<!-- -->//Subclass
    //1. The @Override annotation is placed on the fly method, indicating that the fly method of the subclass overrides the fly method of the parent class.
    //2. If @Override is not written here, the parent class fly will still be rewritten.
    //3. If you write the @Override annotation, the compiler will check whether the method really overrides the parent class's
    // Method, if it is indeed rewritten, the compilation will pass, if it is not overridden, a compilation error will occur.
    //4. Look at the definition of @Override
    // Interpretation: If @interface is found to represent an annotation class
    /*
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public @interface Override {
    }
    */
    @Override //Description
    public void fly() {<!-- -->
        System.out.println("Son fly....");
    }
    @Override
    public void say() {<!-- -->}
}
2. @Override usage instructions
  1. @Override means specifying a method to override the parent class (which can be verified from the compilation level). If the parent class does not have a fly method, an error will be reported.
  2. If you do not write the @Override annotation and the parent class still has public void fly() {}, it still constitutes an override.
  3. @Override can only modify methods, not other classes, packages, properties, etc.
  4. View the source code of the @Override annotation. It is @Target(ElementType.METHOD), indicating that only methods can be modified.
  5. Target is an annotation that decorates annotations, called meta-annotations
3. @Deprecated annotation case
public class Deprecated_ {<!-- -->
    public static void main(String[] args) {<!-- -->
        A a = new A();
        a.hi();
        System.out.println(a.n1);
    }
}
@Deprecated
//1. @Deprecated modifies an element to indicate that the element is outdated
//2. That is, it is no longer recommended, but it can still be used.
//3. View the source code of the @Deprecated annotation class
    /*
    @Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, MODULE, PARAMETER, TYPE})
public @interface Deprecated {
}
    * */
//4. Old version is too compatible
class A {<!-- -->
    public int n1 = 10;
    public void hi() {<!-- -->

    }
}
4. @SuppressWarnings annotation case
import java.util.ArrayList;
import java.util.List;
public class SuppressWarnings_ {<!-- -->
    //1. When we don’t want to see warnings, we can use the @SuppressWarnings annotation to suppress warnings.
    //2. In {""}, you can write the warning you want (not displayed)
    //3. Regarding SuppressWarnings, the scope is related to the location where you place it.
    //4. Placement: TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, MODULE
    @SuppressWarnings({<!-- -->"rawtypes","unchecked","unused"})
    public static void main(String[] args) {<!-- -->
        List list = new ArrayList();
        list.add("jack");
        list.add("tom");
        list.add("mary");
        int i;
        System.out.println(list.get(1));
    }
}
/*
Introduction to attributes and attribute descriptions in @SuppressWarning

all, suppress all warnings
boxing, suppressing warnings related to packaging/disassembly operations
cast, suppresses warnings related to cast jobs
dep-ann, suppress warnings related to deprecated annotations
deprecation, suppress and eliminate related warnings
fallthrough, suppresses warnings related to missing break in switch statements
finally, suppresses warnings related to finally blocks not being returned
hiding, suppresses warnings related to local variables of hidden variables
incomplete-switch, suppresses warnings related to missing items in switch statements (enum cases)
javadoc, suppress javadoc related warnings
nls, suppress warnings related to non-nls string literals
null, suppresses warnings related to null analysis
rawtypes, suppress warnings related to using raw types
resource, suppresses warnings related to using resources of type Closeable
restriction, suppress warnings related to use of deprecated or forbidden references
serial, suppresses warnings related to serializable classes missing the serialVersionUID field
static-access, suppress warnings related to incorrect static access
static-method, suppress warnings related to methods that may be declared static
super, suppresses warnings related to substitution methods without super calls
synthetic-access, suppresses warnings related to unoptimized access to internal classes
sync-override, suppresses warnings about missing synchronization due to overriding synchronization methods
unchecked, suppresses warnings related to unchecked jobs
unqualified-field-access, suppresses warnings related to unqualified field access
unused, suppresses warnings related to unused and deactivated code

 */

9. JDK’s meta-annotation (meta-annotation understanding)

1. Basic introduction to meta-annotations

? JDK’s meta Annotation is used to modify other Annotations
? Meta-annotation: It is not very useful in itself, but it needs to be understood.

2. Types of meta-annotations (not used much, no need to understand them in depth)
  1. Retention: Specify the scope of the annotation, three types: SOURCE, CLASS, RUNTIME
  2. Target: Specify where annotations can be used
  3. Documented: Specifies whether the annotation will be reflected in javadoc
  4. Inherited: Subclasses will inherit parent class annotations
3. @Retention annotation
1. Description

? can only be used to modify an Annotation definition to specify how long the Annotation can be retained. @Rentention contains a member variable of type RetentionPolicy. When using @Rentention, a value must be specified for the value member variable.

2. Three values of @Retention
  1. RetentionPolicy.SOURCE: After the compiler uses it, it directly discards the annotation of this policy.

  2. RetentionPolicy.CLASS: The compiler will record the annotations in the class file. When running the Java program, the JVM will not retain the annotations. It’s the default value

  3. RetentionPolicy.RUNTIME: The compiler will record the annotation in the class file. When running the Java program, the JVM will retain the annotation. The program can obtain the annotation through reflection

3. @Target annotation
  1. Basic instructions

    Used to modify the Annotation definition and specify which program elements the modified Annotation can be used to modify. @Target also contains a member variable named value.

4. @Documented annotation
  1. Basic instructions

    @Documented: used to specify that the Annotation class modified by this meta-Annotation will be extracted into a document by the javadoc tool, that is, the annotation can be seen when the document is generated.

    Note: Annotations defined as Documented must set the Retention value to RUNTIME

5. @Inherited
  1. Basic instructions

    The Annotation modified by it will have inheritance if a class is modified by @Inherited
    Annotation, then its subclasses will automatically have this annotation