Enum private Constructor

enum has constructor. This constructor is private. Why do we need a private constructor? because enum has finite values.  If the constructor is public , anyone can change the values of enum. It can increase the values  This would extend the initial values of enum. 

It is a compile time error if the constructor of an enum type is declared as public or protected.  If no access modifier is specified for the constructor of an enum type, The constructor is by default private.


package com.simple public enum BankAccount     AXIS ("Axis Bank Account"),   DENA ("Dena Bank Account"),   HDFC ("Hdfc Bank Account");   private final String desc;   BankAccount  (String  desc) {       this.desc = desc;      }   public String getDesc(){      return desc;   }


Here we have a BankAccount constructor without any access modifier. In case of enum is by default private.  

But in case of class declaration constructor without access modifier will be considered as  default

package com.simple public class EnumUnderstanding   public static void (String [] args) {   for (BankAccount acc : BankAccount.values()) {     System.out.println ("Account " + acc + "values" + acc.getDec())}


Comments

Popular posts from this blog

Predicate The Functional interface in java

NodeJS vs Java

JPA mappedBy and JoinColumn