当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Enum name()用法及代码示例


Enum 类的 name() 方法返回与在其枚举声明中声明的相同的枚举常量的名称。

toString() 方法主要由程序员使用,因为与 name() 方法相比,它可能返回更易于使用的名称。

用法

public final String name()

返回值

name() 方法返回此枚举的名称。

例子1

enum Herbivores{
Deer,Elephants,Horse,Sheep,Cow;
    }
enum Carnivores{
Lion,Leopard,Wolf,lizard;
    }
enum Omnivores{
Bear,Dog,Cat;
    }
public class Enum_nameMethodExample1 {
public static void main(String[] args) {
       Herbivores Cow =Herbivores.Cow;
       Carnivores Leopard = Carnivores.Leopard;
       Omnivores Bear = Omnivores.Bear;
System.out.println("1. "+Cow.name()+" is in "+ Cow.getClass()+" enum class");
//returns the class object corresponding to the enum constant Wolf
System.out.println("2. "+Leopard.name()+" is in "+ Leopard.getClass()+" enum class");
//returns the class object corresponding to the enum constant Bear
System.out.println("3. "+Bear.name()+" is in "+ Bear.getClass()+" enum class");
    }
}

输出:

1. Cow is in class com.javaTpoint.Enum_nameMethodExample1$Herbivores enum class
2. Leopard is in class com.javaTpoint.Enum_nameMethodExample1$Carnivores enum class
3. Bear is in class com.javaTpoint.Enum_nameMethodExample1$Omnivores enumclas

例子2

enum Triangles{

Right_Angle_Triangle("90"), Obtuse_Angled_Trianlge("greater than 90"),Acutee_Angled_Trianlge("less than 90");

        String angle;

Triangles(String m) {

angle  = m;
        }

        String showAngle() {

return angle;
        }
    }

public class Enum_nameMethodExample2 {

public static void main(String[] args) {

System.out.println("Types of Triangles:");


for(Triangles m:Triangles.values()) {

// name() method will parse the name of the enum constant

System.out.println(m.name() + " is a triangle in which one angle is " + m.showAngle() + " degree.");

            }
        }
    }

输出:

Types of Triangles:
Right_Angle_Triangle is a triangle in which one angle is 90 degree.
Obtuse_Angled_Trianlge is a triangle in which one angle is greater than 90 degree.
Acutee_Angled_Trianlge is a triangle in which one angle is less than 90 degree.

例子3

enum Polygons{

Circles(0), Triangles(3),Quadrilaterals(4),Pentagon(5);

int side;

Polygons(int s){

side=s;
    }

int getSide(){

return side;
    }
        }

public class Enum_nameMethodExample3 {

public static void main(String[] args) {

for(Polygons s:Polygons.values()){

System.out.println(s.name()+" has " +s.getSide()+" sides." );        }
    }
}

输出:

Circles has 0 sides.
Triangles has 3 sides.
Quadrilaterals has 4 sides.
Pentagon has 5 sides.



相关用法


注:本文由纯净天空筛选整理自 Java Enum name() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。