文章目录
1.枚举(enum)
枚举是一组常量的集合,里面包含一组有限的特定的对象,通常全部大写。
自定义枚举类型
- 构造器私有化
- 类内部创建一组对象,使用public static final修饰
- 提供get方法,不提供set方法
package enmu;
public class Enmu01 {
public static void main(String[] args) {
System.out.println(Enum01_.E1);//Enum01_{a=1}
System.out.println(Enum01_.E1.getA());//1
}
}
class Enum01_{
private int a;
public static final Enum01_ E1 = new Enum01_(1);
private Enum01_(int a) {
this.a = a;
}
public int getA() {
return a;
}
@Override
public String toString() {
return "Enum01_{" +
"a=" + a +
'}';
}
}
enum
- class变enum
- 定义的常量类型在最前面
- 多个常量用,分割
- 无参构造可以省略()
- 枚举类默认继承Enum类,所以不能继承其他类,可以实现接口
- E1(1), E2(2), E3是对象
- 默认toString返回常量名
package enmu;
public class Enmu01 {
public static void main(String[] args) {
System.out.println(Enum01_.E1);//Enum01_{a=1}
System.out.println(Enum01_.E2);//Enum01_{a=2}
System.out.println(Enum01_.E1.getA());//1
System.out.println(Enum01_.E2.getA());//2
}
}
enum Enum01_ {
//1.class变enum
//2.定义的常量类型在最前面
//3.多个常量用,分割
//4.无参构造可以省略()
E1(1), E2(2), E3;
private int a;
Enum01_() {
}
private Enum01_(int a) {
this.a = a;
}
public int getA() {
return a;
}
@Override
public String toString() {
return "Enum01_{" +
"a=" + a +
'}';
}
}
2.注解
@interface注解类
修饰注解的注解是元注解
- Retention 指定注解的作用范围
- Target 指定注解的使用地方
- Documented 指定注解是否在Javadoc体现
- Inherited 子类会继承父类注解
@Override重写方法的注解,重写了父类编译通过,没有重写报错。只能用于方法,因为@Target(ElementType.METHOD)
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@Deprecated表示某个元素已过时,新旧版本的过渡
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value={CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, PARAMETER, TYPE})
public @interface Deprecated {
}
@SuppressWarnings抑制警告,传入一个数组
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
@Retention(RetentionPolicy.SOURCE)
public @interface SuppressWarnings {
/**
* The set of warnings that are to be suppressed by the compiler in the
* annotated element. Duplicate names are permitted. The second and
* successive occurrences of a name are ignored. The presence of
* unrecognized warning names is <i>not</i> an error: Compilers must
* ignore any warning names they do not recognize. They are, however,
* free to emit a warning if an annotation contains an unrecognized
* warning name.
*
* <p> The string {@code "unchecked"} is used to suppress
* unchecked warnings. Compiler vendors should document the
* additional warning names they support in conjunction with this
* annotation type. They are encouraged to cooperate to ensure
* that the same names work across multiple compilers.
* @return the set of warnings to be suppressed
*/
String[] value();
}
ross multiple compilers.
* @return the set of warnings to be suppressed
*/
String[] value();
}