目录
3.为什么用关键词"enum"自定义的枚举类不能继承其他类?
枚举类
1.为什么我们需要枚举类
- 当一个类可以被创建的对象有明确的限定时,我们更倾向于使用枚举类,比如创建一个类来表示季节时,我们可以很明确季节只能有春天,夏天,秋天,冬天这四个对象实例,因此我们倾向于使用枚举类来避免一些奇怪的对象实例产生(如果你想,季节都可以有今天,明天和昨天.).
2.如何自定义一个枚举类
两种方式
1.创建类并在类中创建静态公开对象,私有化构造器,并不提供set()相关方法:
class Season {
private String name;
public static final Season SPRING = new Season("春天");
public static final Season SUMMER = new Season("夏天");
public static final Season AUTUMN = new Season("秋天");
public static final Season WINTER = new Season("冬天");
private Season(String name){
this.name = name;
}
public String getName() {
return name;
}
}
2. 用关键词"enum"自定义枚举类:
注意:1.定义常量变量要放在最前面,且默认被 public static final 修饰;
2.如果有多个变量用" , "间隔;
3.无参构造可省略();
enum Season {
SPRING("春天"),SUMMER("夏天"),AUTUMN("秋天"),WINTER("冬天"),SEASON;
private String name;
private Season(String name){
this.name = name;
}
private Season(){}
public String getName() {
return name;
}
}
3.为什么用关键词"enum"自定义的枚举类不能继承其他类?
- 因为用关键词"enum"自定义的枚举类默认继承了Enum这个父类;
- 虽然用关键词"enum"自定义的枚举类无法继承其他类,但是仍可以通过实现接口来对单继承体系进行一个补充;
4.Enum父类常用的方法(附加源码)
- toString():返回当前对象名,子类可以重写
/**
* Returns the name of this enum constant, as contained in the
* declaration. This method may be overridden, though it typically
* isn't necessary or desirable. An enum type should override this
* method when a more "programmer-friendly" string form exists.
*
* @return the name of this enum constant
*/
public String toString() {
return name;
}
- name():返回当前对象名,但是子类无法重写
/**
* Returns the name of this enum constant, exactly as declared in its
* enum declaration.
*
* <b>Most programmers should use the {@link #toString} method in
* preference to this one, as the toString method may return
* a more user-friendly name.</b> This method is designed primarily for
* use in specialized situations where correctness depends on getting the
* exact name, which will not vary from release to release.
*
* @return the name of this enum constant
*/
public final String name() {
return name;
}
- ordinal():返回当前对象的位置值(编号),默认从0开始
/**
* Returns the ordinal of this enumeration constant (its position
* in its enum declaration, where the initial constant is assigned
* an ordinal of zero).
*
* Most programmers will have no use for this method. It is
* designed for use by sophisticated enum-based data structures, such
* as {@link java.util.EnumSet} and {@link java.util.EnumMap}.
*
* @return the ordinal of this enumeration constant
*/
public final int ordinal() {
return ordinal;
}
- values():返回当前枚举类中的所有的枚举对象(源码中没有,但是反编译时可以看到)
- valueOf(): 将字符串转换成该枚举对象,且该字符串的值要和枚举类中的枚举对象中的一个重名,否则会报错
/**
* Returns the enum constant of the specified enum type with the
* specified name. The name must match exactly an identifier used
* to declare an enum constant in this type. (Extraneous whitespace
* characters are not permitted.)
*
* <p>Note that for a particular enum type {@code T}, the
* implicitly declared {@code public static T valueOf(String)}
* method on that enum may be used instead of this method to map
* from a name to the corresponding enum constant. All the
* constants of an enum type can be obtained by calling the
* implicit {@code public static T[] values()} method of that
* type.
*
* @param <T> The enum type whose constant is to be returned
* @param enumType the {@code Class} object of the enum type from which
* to return a constant
* @param name the name of the constant to return
* @return the enum constant of the specified enum type with the
* specified name
* @throws IllegalArgumentException if the specified enum type has
* no constant with the specified name, or the specified
* class object does not represent an enum type
* @throws NullPointerException if {@code enumType} or {@code name}
* is null
* @since 1.5
*/
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name) {
T result = enumType.enumConstantDirectory().get(name);
if (result != null)
return result;
if (name == null)
throw new NullPointerException("Name is null");
throw new IllegalArgumentException(
"No enum constant " + enumType.getCanonicalName() + "." + name);
}
- compareTo():比较两个枚举常量的编号,返回值为两个枚举常量的位置值之差(前减后)
/**
* Compares this enum with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
*
* Enum constants are only comparable to other enum constants of the
* same enum type. The natural order implemented by this
* method is the order in which the constants are declared.
*/
public final int compareTo(E o) {
Enum<?> other = (Enum<?>)o;
Enum<E> self = this;
if (self.getClass() != other.getClass() && // optimization
self.getDeclaringClass() != other.getDeclaringClass())
throw new ClassCastException();
return self.ordinal - other.ordinal;
}