zoukankan      html  css  js  c++  java
  • Java Enumeration

    ref: http://www.studytonight.com/java/enumerations

    Enumerations

    Enumeration was added to Java language in JDK5. Enumeration means a list is named constant. In java, enumeration

    defines a class type. An Enumeration can have constructors, methods and instance variables. It is created using

    enum keyword. Each enumeration constant is public, static and final by default.

    Even though enumeration defines a class type and have constructors, you do not instantiate an enum using new. 

    Enumeration variables are used and declared in much a same way as you do in primitive variables

    How to Define and Use an Enumeration

    enum Subject           //Enumeration defined
    {
     Java, Cpp, C, Dbms
    }


    1. Java, Cpp, C, Dbms are called enumeration constants. They are public,static, final by default

    2. variable of enumeration can be defined directly without new keyword

    Subject sub

    3. variable of enumeration type can have only enumeration constants as value

      sub = Subject.java;


    Values( ) and ValueOf( ) method

    All the enumerations has values() and valueOf() methods inthem. 

    values() :method returns an array of enum-type containing all the enumeration constants in it.

      public static enum-type[] values()

    valueOf(): method is used to return enumeration constant whose value is equal to the string passed in as argument while calling this method

      public static enum-type valueOf(String str)

    Points to remember about Enumerations

    1. Enumeration are of class type, and have all capabilities taht a java class has

    2. Enumerations can have constructors, instance variables, methods and can even implement interfaces

    3. Enumerations are not instantiated using new 

    4. All Enumerations by default inherite java.lang.Enum class

    enum Student
    {
     John(11), Bella(10), Sam(13), Viraaj(9);
     private int age;                   //age of students
     int getage { return age; }
     public Student(int age)
     {
      this.age= age;
     }
    }
    
    class EnumDemo
    {
     public static void main( String args[] )
     {
      Student S;
      System.out.println("Age of Viraaj is " +Student.Viraaj.getage()+ "years");
     }
    }

    Output :
    Age of Viraaj is 9 years






  • 相关阅读:
    Redis源码剖析之字典(dict)
    Redis源码剖析之跳表(skiplist)
    面试题精选:神奇的斐波那契数列
    awk实现类sql的join操作
    [翻译]CAP理论及其证明
    今年是冷冬?我爬了北京10年的气温,哟 还真是!
    python 等间隔抽取一定数量的数据
    操作系统-第十章-文件系统
    操作系统-第九章-虚拟内存管理
    操作系统-第八章-内存管理
  • 原文地址:https://www.cnblogs.com/morningdew/p/5619728.html
Copyright © 2011-2022 走看看