Java Study Notes (11) Chapter 11 - Enumerations and Annotations

11.1 Look at a requirement first

It is required to create a Season object, please design and complete it.

There is a problem with the following code design. Because it is only for the season, his objects (specific values) are fixed at four, and there will be no more. According to the idea of ​​the design class below, it cannot reflect the four fixed objects of the season. Therefore, such a design is not good, leading to enumeration ===> enumeration class [enumeration: one by one: enumeration, that is, the class that enumerates specific objects one by one is called an enumeration class]

public class LianXi {
    
    
    public static void main(String[] args) {
    
    
        //使用
        Season spring = new Season("春天", "温暖");
        Season winter = new Season("冬天", "寒冷");
        Season summer = new Season("夏天", "炎热");
        Season autumn = new Season("秋天", "凉爽");
        Season other =  new Season("红天", "~~~");
//        autumn.setName("XXX");
//        autumn.setDesc("非常的热.."); //修改值
        //因为对于季节而已,他的对象(具体值),是固定的四个,不会有更多
        //按老师的这个设计类的思路,不能体现季节是固定的四个对象
  //因此,这样的设计不好===> 枚举类[枚: 一个一个 举: 例举 , 即把具体的对象一个一个例举出来的类 就称为枚举类]
       
    }
}
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;}
}

11.2 Analyzing the problem

  1. Creating a Season object has the following characteristics
    (1) The value of the season is limited to several values ​​(spring, summer, autumn, winter)
    (2) It is read-only and does not need to be modified.
  2. Solution - Enumeration
    (1) Enumeration corresponds to English (enumeration, abbreviated enum)
    (2) Enumeration is a collection of constants.
    (3) It can be understood here: enumeration belongs to a special class, which only contains a limited set of specific objects.
  3. Two implementations of enumeration
    (1) Custom class implementation of enumeration
    (2) Enumeration implementation using the enum keyword

11.3 Custom class implements enumeration

  1. There is no need to provide setXxx methods because enum object values ​​are usually read-only.
  2. Use final + static joint decoration for enumeration objects/properties to achieve bottom-level optimization.
  3. Enumeration object names usually use all uppercase, constant naming conventions.
  4. The enumeration object can also have multiple attributes according to the needs //Enumeration02.java
  • Custom class implements enumeration - summary

    Summary: Enumeration of custom classes has the following characteristics:
    (1) Private constructor
    (2) Create a group of objects inside this class [four spring, summer, autumn and winter]
    (3) Expose objects to the outside world (by adding public final static modifier)
    ​​(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(Season.AUTUMN);
        System.out.println(Season.SPRING);
    }
}

//演示字定义枚举实现
class Season {
    
    //类
    private String name;
    private String desc;//描述

    //定义了四个对象, 固定.
    public static final Season SPRING = new Season("春天", "温暖");
    public static final Season WINTER = new Season("冬天", "寒冷");
    public static final Season AUTUMN = new Season("秋天", "凉爽");
    public static final Season SUMMER = new Season("夏天", "炎热");


    //1. 将构造器私有化,目的防止 直接 new
    //2. 去掉setXxx方法, 防止属性被修改
    //3. 在Season 内部,直接创建固定的对象
    //4. 优化,可以加入 final 修饰符
    private Season(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 "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
   }
}

11.4 The enum keyword implements enumeration - quick start, classroom exercises

Explanation: Use enum to realize the previous enumeration case, see the code demonstration, and mainly experience the differences from the custom class implementation of enumeration.

  • The enum keyword implements enumeration considerations
  1. When we use the enum keyword to develop an enumeration class, the Enum class will be inherited by default, and it is a final class [how to prove], use the javap tool to demonstrate
  2. The traditional public static final Season2 SPRING = new Season2("spring", "warm"); can be simplified to SPRING("spring", "warm"), where you must know which constructor it calls.
  3. If an enumeration object is created using a no-argument constructor, both the actual parameter list and the parentheses can be omitted
  4. When there are multiple enumeration objects, use , to separate them, and end with a semicolon
  5. The enumeration object must be placed at the beginning of the line of the enumeration class.
    insert image description here
    Code:
public class Enumeration03 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Season2.AUTUMN);
        System.out.println(Season2.SUMMER);
    }
}
//演示使用enum关键字来实现枚举类
enum  Season2 {
    
    //类
    //定义了四个对象, 固定.
    //如果使用了enum 来实现枚举类
    //1. 使用关键字 enum 替代 class
    //2. public static final Season SPRING = new Season("春天", "温暖") 直接使用
    //   SPRING("春天", "温暖") 解读 常量名(实参列表)
    //3. 如果有多个常量(对象), 使用 ,号间隔即可
    //4. 如果使用enum 来实现枚举,要求将定义常量对象,写在前面
    //5. 如果我们使用的是无参构造器,创建常量对象,则可以省略 ()
    SPRING("春天", "温暖"), WINTER("冬天", "寒冷"), AUTUMN("秋天", "凉爽"),
    SUMMER("夏天", "炎热") ,WHAT/*, What()*/;

    private String name;
    private String desc;//描述

    private Season2() {
    
    //无参构造器 }
    private Season2(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 "Season{" +
                "name='" + name + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}
  • classroom exercises
  1. Is the following code correct and explain what it means?

    enum Gender{ //1min
    BOY , GIRL; //This is actually calling the no-argument constructor of the Gender class
    }
    (1) The syntax above is ok
    (2) There is an enumeration class Gender without attributes.
    (3) There are two enumerated objects BOY, GIRL, created using a no-argument constructor.

  2. What does the following code output? EnumExercise01.java
    insert image description here

11.5 Description of common enum methods and classroom exercises

  • Explanation: When the keyword enum is used, the Enum class will be inherited implicitly, so that we can use the methods related to the Enum class. [Look at the source code definition.]
    public abstract class Enum<E extends Enum>
    implements Comparable, Serializable { } Let's illustrate the use of enum's commonly used methods and test Season2. EnumMethod.java

  1. toString: The Enum class has been rewritten, and it returns the current object name. Subclasses can rewrite this method to return the attribute information of the object
  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 class
  5. valueOf: Convert a string to an enumeration object, requiring the string to be an existing constant name, otherwise an exception will be reported!
  6. compareTo: Compare two enumeration constants, the comparison is the number!
public class EnumMethod {
    
    
    public static void main(String[] args) {
    
    
        //使用Season2 枚举类,来演示各种方法
        Season2 autumn = Season2.AUTUMN;

        //输出枚举对象的名字
        System.out.println(autumn.name());
        //ordinal() 输出的是该枚举对象的次序/编号,从0开始编号
        //AUTUMN 枚举对象是第三个,因此输出 2
        System.out.println(autumn.ordinal());
        //从反编译可以看出 values方法,返回 Season2[]
        //含有定义的所有枚举对象
        Season2[] values = Season2.values();
        System.out.println("===遍历取出枚举对象(增强for)====");
        for (Season2 season: values) {
    
    //增强for循环,末尾与详解
            System.out.println(season);
        }

        //valueOf:将字符串转换成枚举对象,要求字符串必须为已有的常量名,否则报异常
        //执行流程
        //1. 根据你输入的 "AUTUMN" 到 Season2的枚举对象去查找
        //2. 如果找到了,就返回,如果没有找到,就报错
        Season2 autumn1 = Season2.valueOf("AUTUMN");
        System.out.println("autumn1=" + autumn1);
        System.out.println(autumn == autumn1);//true 是同一个对象

        //compareTo:比较两个枚举常量,比较的就是编号
        //解读
        //1. 就是把 Season2.AUTUMN 枚举对象的编号 和 Season2.SUMMER枚举对象的编号比较
        //2. 看看结果
        /* 原码
        public final int compareTo(E o) {

            return self.ordinal - other.ordinal;
        }
        Season2.AUTUMN的编号[2] - Season2.SUMMER的编号[3]
         */
        System.out.println(Season2.AUTUMN.compareTo(Season2.SUMMER));

        //补充了一个增强for
//        int[] nums = {1, 2, 9};
//        //普通的for循环
//        System.out.println("=====普通的for=====");
//        for (int i = 0; i < nums.length; i++) {
    
    
//            System.out.println(nums[i]);
//        }
//        System.out.println("=====增强的for=====");
//        //执行流程是 依次从nums数组中取出数据,赋给i, 如果取出完毕,则退出for
//        for(int i : nums) {
    
    
//            System.out.println("i=" + i);
//        }
    }
}
enum  Season2 {
    
    //类

    SPRING("春天", "温暖"), WINTER("冬天", "寒冷"), AUTUMN("秋天", "凉爽"),
    SUMMER("夏天", "炎热");

    private String name;
    private String desc;//描述

    private Season2(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 "Season{" +
                    "name='" + name + '\'' +
                    ", desc='" + desc + '\'' +
                    '}';
        }
    }
  • classroom exercises

    Declare the Week enumeration class, which contains the definition of Monday to Sunday; MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY; use values ​​to return all enumeration arrays, and traverse. It is required to return "Monday"-"Sunday" (when rewriting toString, just delete it, leaving only the name)

public class EnumExercise02 {
    
    
    public static void main(String[] args) {
    
    
        //获取到所有的枚举对象, 即数组
        Week[] weeks = Week.values();
        //遍历,使用增强for
        System.out.println("===所有星期的信息如下===");
        for (Week week : weeks) {
    
    
            System.out.println(week);
        }
    }
}

enum Week   {
    
    
    //定义Week的枚举对象
    MONDAY("星期一"), TUESDAY("星期二"), WEDNESDAY("星期三"), THURSDAY("星期四"),
    FRIDAY("星期五"), SATURDAY("星期六"), SUNDAY("星期日");
    private String name;

    private Week(String name) {
    
    //构造器
        this.name = name;
    }
    @Override
    public String toString() {
    
    
        return name;
    }
}

11.6 enum implements interface

EnumDetail.java

  1. After using the enum keyword, you can no longer inherit other classes, because enum will implicitly inherit Enum, and Java is a single inheritance mechanism.
  2. Enumeration classes, like ordinary classes, can implement interfaces, as follows.
    enum class name implements interface 1, interface 2{}
public class EnumDetail {
    
    
    public static void main(String[] args) {
    
    
        Music.CLASSICMUSIC.playing();
    }
}
class A {
    
    
}
//1.使用enum关键字后,就不能再继承其它类了,因为enum会隐式继承Enum,而Java是单继承机制
//enum Season3 extends A { //这样是错的
//
//}
//2.enum实现的枚举类,仍然是一个类,所以还是可以实现接口的.
interface IPlaying {
    
    
    public void playing();
}
enum Music implements IPlaying {
    
    
    CLASSICMUSIC;  //省略了括号,默认调无参构造器
    @Override
    public void playing() {
    
    
        System.out.println("播放好听的音乐...");
    }
}

11.7 Comprehension of annotations, introduction to basic Annotation

  • Understanding of 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 annotations, annotations do not affect program logic, but annotations can be compiled or run, which is equivalent to supplementary information embedded in the code.
  3. In JavaSE, annotations are used for simple purposes, such as marking obsolete functions, ignoring warnings, etc. Annotations occupy a more important role in JavaEE, for example, to configure any aspect of the application, replacing the cumbersome code and XML configuration left in the old version of java EE.
  • Basic Annotation Introduction

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

    Three basic Annotations:
    (1) @Override: Limit a method, which is to override the parent class method, this annotation can only be used for methods
    (2) @Deprecated: Used to represent a certain program element (class, method, etc.) Obsolete
    (3) @SuppressWarnings: suppress compiler warnings

11.7.1 Instructions and cases of @Override annotation

  • @Override Instructions

@Override: To limit a method is to override the parent class method, and this annotation can only be used for methods

  1. @Override means to specify the method of overriding the parent class (verified from the compilation level), if the parent class does not have a fly method, an error will be reported
  2. If the @Override annotation is not written, and the parent class still has public void fly(), it still constitutes rewriting
  3. @Override can only modify methods, not other classes, packages, properties, etc.
  4. Check the @Override annotation source code as @Target(ElementType.METHOD), indicating that only methods can be modified
  5. @Target is an annotation that modifies annotations, called meta-annotations , remember this concept.
  • Case demonstration Override_.java

    Supplementary note: The description of @interface
    @interface is not an interface, but an annotation class, which was added after jdk5.0

public class Override_ {
    
    
    public static void main(String[] args) {
    
    
    }
}
class Father{
    
    //父类
    public void fly(){
    
    
        int i = 0;
        System.out.println("Father fly...");
    }
}

class Son extends Father {
    
    //子类
    //解读
    //1. @Override 注解放在fly方法上,表示子类的fly方法时重写了父类的fly
    //2. 这里如果没有写 @Override 还是重写了父类fly
    //3. 如果你写了@Override注解,编译器就会去检查该方法是否真的重写了父类的
    //   方法,如果的确重写了,则编译通过,如果没有构成重写,则编译错误
    //4. 看看 @Override的定义
    //   解读: 如果发现 @interface 表示一个 注解类
    /*
        @Target(ElementType.METHOD)
        @Retention(RetentionPolicy.SOURCE)
        public @interface Override {
        }
     */
    @Override   //说明
    public void fly() {
    
    
        System.out.println("Son fly....");
    }

   // @Override  父类没有say()方法,写了 @Override 就报错
    public void say() {
    
    }
}

11.7.2 Instructions and cases of @Deprecated annotation

Deprecated_.java

@Deprecated: Used to indicate that a certain program element (class, method, etc.) has outdated code, but it can still be used when it is outdated.

Explanation of @Deprecated

  1. Used to indicate that a certain program element (class, method, etc.) is obsolete
  2. You can modify methods, classes, fields, packages, parameters, etc.
  3. @Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE,METHOD,PACKAGE, PARAMETER, TYPE)
  4. The role of @Deprecated can achieve compatibility and transition between old and new versions
public class Deprecated_ {
    
    
    public static void main(String[] args) {
    
    
        A a = new A();
        a.hi();
        System.out.println(a.n1);
    }
}
//解读
//1. @Deprecated 修饰某个元素, 表示该元素已经过时
//2. 即不在推荐使用,但是仍然可以使用
//3. 查看 @Deprecated 注解类的源码
//4. 可以修饰方法,类,字段, 包, 参数  等等
//5. @Deprecated 可以做版本升级过渡使用
/*
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR 构造器, FIELD 字段 也就是属性, LOCAL_VARIABLE 局部变量,
        METHOD, PACKAGE, PARAMETER 参数 , TYPE 类型 也就是类})
public @interface Deprecated {
}
 */
@Deprecated
class A {
    
    
    @Deprecated
    public int n1 = 10;
    @Deprecated
    public void hi(){
    
    
    }
}

11.7.3 Case of @SuppressWarnings annotation

SuppressWarnings_.java

@SuppressWarnings: suppress compiler warnings

To illustrate the various values:

  1. unchecked is to ignore unchecked warnings
  2. rawtypes ignores warnings that do not specify generics (warning errors that do not specify generics when passing parameters)
  3. unused is to ignore warning errors that do not use a variable
  4. The program elements that @SuppressWarnings can modify are, see @Target
  5. When generating @SupperssWarnings, you don’t need to memorize it, just click the yellow prompt on the left to select it (note that you can specify the generated location)
import java.util.ArrayList;
import java.util.List;

@SuppressWarnings({
    
    "rawtypes", "unchecked", "unused"})
public class SuppressWarnings_ {
    
    
    //解读
    //1. 当我们不希望看到这些警告的时候,可以使用 SuppressWarnings注解来抑制警告信息
    //2. 在{""} 中,可以写入你希望抑制(不显示)警告信息
    //3. 可以指定的警告类型有
    //          all,抑制所有警告
    //          boxing,抑制与封装/拆装作业相关的警告
    //        //cast,抑制与强制转型作业相关的警告
    //        //dep-ann,抑制与淘汰注释相关的警告
    //        //deprecation,抑制与淘汰的相关警告
    //        //fallthrough,抑制与switch陈述式中遗漏break相关的警告
    //        //finally,抑制与未传回finally区块相关的警告
    //        //hiding,抑制与隐藏变数的区域变数相关的警告
    //        //incomplete-switch,抑制与switch陈述式(enum case)中遗漏项目相关的警告
    //        //javadoc,抑制与javadoc相关的警告
    //        //nls,抑制与非nls字串文字相关的警告
    //        //null,抑制与空值分析相关的警告
    //        //rawtypes,抑制与使用raw类型相关的警告
    //        //resource,抑制与使用Closeable类型的资源相关的警告
    //        //restriction,抑制与使用不建议或禁止参照相关的警告
    //        //serial,抑制与可序列化的类别遗漏serialVersionUID栏位相关的警告
    //        //static-access,抑制与静态存取不正确相关的警告
    //        //static-method,抑制与可能宣告为static的方法相关的警告
    //        //super,抑制与置换方法相关但不含super呼叫的警告
    //        //synthetic-access,抑制与内部类别的存取未最佳化相关的警告
    //        //sync-override,抑制因为置换同步方法而遗漏同步化的警告
    //        //unchecked,抑制与未检查的作业相关的警告
    //        //unqualified-field-access,抑制与栏位存取不合格相关的警告
    //        //unused,抑制与未用的程式码及停用的程式码相关的警告
    //4. 关于SuppressWarnings 作用范围是和你放置的位置相关
    //   比如 @SuppressWarnings放置在 main方法,那么抑制警告的范围就是 main
    //   通常我们可以放置具体的语句, 方法, 类.
    //5.  看看 @SuppressWarnings 源码
    //(1) 放置的位置就是 TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE
    //(2) 该注解类有数组 String[] values() 设置一个数组比如 {"rawtypes", "unchecked", "unused"}
    /*
        @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
            @Retention(RetentionPolicy.SOURCE)
            public @interface SuppressWarnings {

                String[] value();
        }
     */
    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));

    }

    public void f1() {
    
    
//        @SuppressWarnings({"rawtypes"})
        List list = new ArrayList();

        list.add("jack");
        list.add("tom");
        list.add("mary");
//        @SuppressWarnings({"unused"})
        int i;
        System.out.println(list.get(1));
    }
}

11.8 Meta-Annotation of JDK (meta-annotation, understanding)

  • Basic introduction of meta-
    annotation JDK's meta-Annotation is used to modify other Annotation
    meta-annotations: It has little effect on its own. I hope that students can know what he does when they look at the source code.

  • Types of meta-annotations (not used much, understand, no need to study in depth)

    (1) Retention //Specify the scope of the annotation, three kinds of SOURCE, CLASS, RUNTIME
    (2) Target //Specify where the annotation can be used
    (3) Documented //Specify whether the annotation will be reflected in javadoc
    (4) Inherited //The subclass will inherit the annotations of the parent class

11.8.1 @Retention annotation

Note
It can only be used to modify an Annotation definition, and is used to specify how long the Annotation can be retained. @Rention contains a
member variable of the RetentionPolicy type. When using @Rention, you must specify a value for the value member variable:
Three values ​​​​of @Retention

  1. RetentionPolicy.SOURCE: After the compiler uses it, it directly discards the comments of this policy
  2. RetentionPolicy.CLASS: The compiler will record the annotations in the class file. When running a 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 a Java program, the JVM will retain the annotation. The program can obtain the annotation through reflection

insert image description here

11.8.2 @Target

insert image description hereinsert image description here

11.8.3 @Documented

insert image description here
insert image description here

11.8.4 @Inherited annotation

Annotation modified by it will have inheritance. If a class uses Annotation modified by @Inherited, its subclasses will automatically have this annotation
Note: In practical applications, it is rarely used, just understand it.
Meta-annotation: It has little effect on its own. I hope that when you look at the source code, you can know what it does.

11.9 Exercises for this chapter

  1. Try to write the execution result of the following code
public class Homework01 {
    
    
    public static void main(String[] args) {
    
    
        Car c =new Car();
        Car c1=new Car(100);
        System.out.println(c);//9.0,red
        System.out.println(c1);//100.0,red
    }
}
class Car{
    
    
    double price=10;
    static String color="white";
    public String toString(){
    
    
        return price+"\t"+color;
    }
    public Car(){
    
    
        this.price=9;
        this.color="red";
    }
    public Car(double price){
    
    
        this.price=price;
    }
}
  1. Programming question Homework02.java 3min requirements -> code

(1) Declare a private static attribute currentNum[int type] in the Frock class, with an initial value of 100000, which is used as the initial value of the serial number of the clothes when they leave the factory.
(2) Declare the public static method getNextNum as the method to generate the unique serial number of the jacket. Every time it is called, increase currentNum by 100 as the return value.
(3) In the main method of the TestFrock class, call the getNextNum method twice to obtain the serial number and print it out.
(4) Declare the serialNumber (serial number) attribute in the Frock class, and provide the corresponding get method; (
5) In the constructor of the Frock class, obtain a unique serial number for the Frock object by calling the getNextNum method, and assign it to the serialNumber attribute.
(6) In the main method of the TestFrock class, create three Frock objects respectively, and print the serial numbers of the three objects to verify whether they are incremented by 100.

public class Homework02 {
    
    
    public static void main(String[] args) {
    
    
    }
}

class Frock {
    
    
    private static  int currentNum = 100000;
    private int serialNumber;

    public Frock() {
    
    
        serialNumber = getNextNum();
    }

    public static int getNextNum() {
    
    
        currentNum += 100; //将currentNum增加100
        return currentNum;
    }

    public int getSerialNumber() {
    
    
        return serialNumber;
    }
}
class TestFrock {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(Frock.getNextNum());//100100
        System.out.println(Frock.getNextNum());//100200
        Frock frock = new Frock();//序列号就是 100300
        Frock frock1 = new Frock();//序列号就是 100400
        Frock frock2 = new Frock();//序列号就是 100500
        System.out.println(frock.getSerialNumber());//100300
        System.out.println(frock1.getSerialNumber());//100400
        System.out.println(frock2.getSerialNumber());//100500
    }
}
  1. Programming questions HomeworkO3.java

    Realize the following problems as required: 1min to complete -> use of abstract classes
    (1) Animal class Animal contains abstract method shout();
    (2) Cat class inherits Animal, and implements method shout, prints "cats can scream"
    (3) The Dog class inherits from Animal, and implements the method shout, printing "the dog will bark"
    (4) Instantiate the object Animal cat = new Cat() in the test class, and call the shout method of cat
    (5) In the test Instantiate the object Animal dog=new Dog0 in the class, and call the dog's shout method

public class Homework03 {
    
    
    public static void main(String[] args) {
    
    
        Animal cat = new Cat();
        Animal dog = new Dog();
        cat.shout();
        dog.shout();
    }
}

abstract class Animal {
    
    //抽象类
    public abstract void shout();
}
class Cat extends Animal {
    
    
    @Override
    public void shout() {
    
    
        System.out.println("猫会喵喵叫");
    }
}
class Dog extends Animal {
    
    
    @Override
    public void shout() {
    
    
        System.out.println("狗会汪汪叫");
    }
}
  1. Programming question Homework04.java 2min
    Investigate the use of anonymous internal classes
    (1) The calculator interface has a work method, the function is calculation, there is a mobile phone class Cellphone, define the method testWork to test the calculation function, and call the work method of the calculation interface, (2
    ) It is required to call the testWork method of the CellPhone object, using the anonymous inner class
public class Homework04 {
    
    
    public static void main(String[] args) {
    
    
        Cellphone cellphone = new Cellphone();
        //解读:匿名内部类是
        /*
            new ICalculate() {
                @Override
                public double work(double n1, double n2) {
                    return n1 + n2;
                }
            }, 同时也是一个对象
            他的编译类型 ICalculate, 他的运行类型就是 匿名内部类
         */
        cellphone.testWork(new ICalculate() {
    
    
            @Override
            public double work(double n1, double n2) {
    
    
                return n1 + n2;
            }
        }, 10, 8);//18.0

        cellphone.testWork(new ICalculate() {
    
    
            @Override
            public double work(double n1, double n2) {
    
    
                return n1 * n2;
            }
        }, 10, 8);
    }
}
//编写接口
interface ICalculate {
    
    
    //work方法 是完成计算,但是题没有具体要求,所以自己设计
    //至于该方法完成怎样的计算,我们交给匿名内部类完成
    public double work(double n1, double n2) ;
}
class Cellphone {
    
    
    //解读,当我们调用testWork方法时,直接传入一个实现了ICalculate接口的匿名内部类即可
    //该匿名内部类,可以灵活的实现work,完成不同的计算任务
    public void testWork(ICalculate iCalculate, double n1, double n2) {
    
    
        double result = iCalculate.work(n1, n2);//动态绑定
        System.out.println("计算后的结果是=" + result);
    }
}
  1. Programming questions HomeworkO5.java
    internal class
    1. Write a class A, define a local internal class B in the class, B has a private final constant name, and a method show () to print the constant name. Conduct test
    2. Advanced: A also defines a private variable name. In the show method, print the test
public class Homework05 {
    
    
    public static void main(String[] args) {
    
    
        new A().f1();
    }
}

class A {
    
    
    private String NAME = "hello";
    public void f1() {
    
    

        class B {
    
     //局部内部类
            private final String NAME = "Java教育";
            public void show() {
    
    
                //如果内部类和外部类的属性重名,可以同 外部类.this.属性名来指定
                System.out.println("NAME=" + NAME + " 外部类的name=" + A.this.NAME);
            }
        }
        B b = new B();
        b.show();
    }
}
  1. Programming questions Homework06.java

    (1) There is a vehicle interface class Vehicles (that is, the interface), and there is a work interface
    (2) There are Horse class and Boat class to implement Vehicles respectively
    (3) Create a vehicle factory class, and there are two methods to obtain the vehicle Horse and Boat
    (4) There is a Person class, with name and Vehicles attributes, and assign values ​​​​to the two attributes in the constructor
    (5) Instantiate the Person object "Tang Seng". It is required to use Horse as a means of transportation under normal circumstances, and use it when encountering a big river. Boat as a means of transportation
    (6) adds a situation, if Tang Seng passes the Flame Mountain, use the plane ==> program scalability, our previous program structure is very easy to expand

The code of the main class and 1-3 small questions

import com.cmLianXi.modifier.A;

public class LianXi {
    
    
    public static void main(String[] args) {
    
    
        Person tang = new Person("唐僧", new Horse());
        tang.common();//一般情况下
        tang.passRiver();//过河
        tang.common();//一般情况下
        tang.passRiver();//过河
        tang.passRiver();//过河
        tang.passRiver();//过河
        //过火焰山
        tang.passFireHill();
    }
}
interface Vehicles{
    
     //第一小问
    public void work();
}

class Horse implements Vehicles{
    
     //第二小问
    @Override
    public void work() {
    
    
        System.out.println(" 一般情况下,使用马儿前进...");
    }
}

class Boat implements Vehicles{
    
    
    @Override
    public void work() {
    
    
        System.out.println(" 过河的时候,使用小船.. ");
    }
}
class Plane implements Vehicles {
    
    
    @Override
    public void work() {
    
    
        System.out.println("过火焰山,使用飞机...");
    }
}

class VehiclesFactory {
    
    
    //马儿始终是同一匹
    private static Horse horse = new Horse(); //饿汉式

    private VehiclesFactory(){
    
    }
    //创建交通工具工厂类,有两个方法分别获得交通工具Horse和Boat
    //这里,我们将方法做成static
    public static Horse getHorse() {
    
    
//        return new Horse();
        return horse;
    }
    public static Boat getBoat() {
    
    
        return new Boat();
    }
    public static Plane getPlane() {
    
    
        return new Plane();
   }
}

Person class code of 4-6 small questions:

public class Person {
    
    
    private String name;
    private Vehicles vehicles;

    //在创建人对象时,事先给他分配一个交通工具
    public Person(String name, Vehicles vehicles) {
    
    
        this.name = name;
        this.vehicles = vehicles;
    }

    //实例化Person对象“唐僧”,要求一般情况下用Horse作为交通工具,遇到大河时用Boat作为交通工具
    //这里涉及到一个编程思路,就是可以把具体的要求,封装成方法-> 这里就是编程思想
    //思考一个问题,如何不浪费,在构建对象时,传入的交通工具对象->动脑筋
    public void passRiver() {
    
     //过河情况
        //先得到船
        //判断一下,当前的 vehicles 属性是null, 就获取一艘船
//        Boat boat = VehiclesFactory.getBoat();
//        boat.work();
        //如何防止始终使用的是传入的马 instanceOf
        //if (vehicles == null) {
    
    
        //vehicles instanceof Boat 是判断 当前的 vehicles是不是Boat
        //(1) vehicles = null  : vehicles instanceof Boat  => false
        //(2) vehicles = 马对象 :vehicles instanceof Boat  => false
        //(3) vehicles = 船对象 :vehicles instanceof Boat  => true
        if (!(vehicles instanceof Boat)) {
    
    
            vehicles = VehiclesFactory.getBoat();
        }
        vehicles.work();
    }
    public void common() {
    
     //一般情况下
        //得到马儿
        //判断一下,当前的 vehicles 属性是null, 就获取一匹马
        //if (vehicles == null) {
    
    
        if (!(vehicles instanceof Horse)) {
    
    
            //这里使用的是多态
            vehicles = VehiclesFactory.getHorse();
        }
        //这里体现使用接口调用
        vehicles.work();
    }
    //过火焰山
    public void passFireHill() {
    
    
        if (!(vehicles instanceof Plane)) {
    
    
            //这里使用的是多态
            vehicles = VehiclesFactory.getPlane();
        }
        //这里体现使用接口调用
        vehicles.work();
    }
}
  1. Internal class practice programming questions HomeworkO7.java

There is a Car class with an attribute temperature (temperature), and an Air (air conditioner) class in the car, which has the function of blowing flow. Air will monitor the temperature in the car and blow air-conditioning if the temperature exceeds 40 degrees. Turn on the heat if the temperature is below 0 degrees, and turn off the air conditioner if it is in between. Instantiate Car objects with different temperatures, call the flow method of the air conditioner, and test whether the air blown by the air conditioner is correct. //Case class that embodies the inclusion relationship between classes and classes (inner class [member inner class])

public class LianXi {
    
    
    public static void main(String[] args) {
    
    
        Car car = new Car(50);
        car.getAir().flow();

        Car car1 = new Car(-1);
        car1.getAir().flow();

        Car car2 = new Car(20);
        car2.getAir().flow();
    }
}

class Car{
    
    
    private double temperature;

    public Car(double temperature) {
    
    
        this.temperature = temperature;
    }

    //Air 成员内部类
    class Air{
    
    
        public void  flow(){
    
    
            if (temperature >= 40){
    
    
                System.out.println("温度大于40 空调吹冷气");
            }else if(temperature < 0){
    
    
                System.out.println("温度低于0度 吹暖气");
            }else{
    
    
                System.out.println("关闭空调");
            }
        }
    }
    //返回一个Air对象
    public Air getAir(){
    
    
        return new Air();
    }
}
  1. Enumeration class programming questions Homework08.java

    (1) Create a Color enumeration class
    (2) There are five enumeration values/objects of RED, BLUE BLACK, YELLOW, GREEN; (
    3) 3. Color has three attributes redValue, greenValue, blueValue,
    (4) Create a structure Method, parameters include these three attributes,
    (5) Each enumeration value must be assigned to these three attributes, and the corresponding values ​​​​of the three attributes are
    (6) red: 255,0,0 blue:0,0,255 black :0,0,0 yellow:255,255,0 green:0,255,0
    (7) Define the interface, there is a method show in it, and Color is required to implement the interface
    (8) The value of the three attributes is displayed in the show method
    (9) The object will be enumerated In the switch statement match use

public class Homework08 {
    
    
    public static void main(String[] args) {
    
    
        //演示一下枚举值得switch使用
        Color green = Color.GREEN;
        green.show();
        //比较一下
        //switch () 中,放入枚举对象
        //在每个case 后,直接写上在枚举类中,定义的枚举对象即可
        switch (green) {
    
    
            case YELLOW:
                System.out.println("匹配到黄色");
                break;
            case BLACK:
                System.out.println("匹配到黑色");
                break;
            default:
                System.out.println("没有匹配到..");
        }
    }
}
interface IMyInterface {
    
    
    public void show();
}

enum Color implements IMyInterface {
    
    
    RED(255, 0, 0), BLUE(0, 0, 255), 
    BLACK(0, 0, 0), YELLOW(255, 255, 0), 
    GREEN(0, 255, 0);
    private int redValue;
    private int greenValue;
    private int blueValue;

    Color(int redValue, int greenValue, int blueValue) {
    
    
        this.redValue = redValue;
        this.greenValue = greenValue;
        this.blueValue = blueValue;
    }
    @Override
    public void show() {
    
    
        System.out.println("属性值为" + redValue + "," + greenValue + "," + blueValue);
    }
}

Guess you like

Origin blog.csdn.net/m0_50736744/article/details/121538972