Saturday, 10 June 2017

Java Tutorial: Enum in java[How to define a constructor and method in enum - mobile] ~ foundjava


Click here to watch in Youtube : 

https://www.youtube.com/watch?v=w3j2BoswQgc&list=UUhwKlOVR041tngjerWxVccw

Mobile.java

enum Mobile
{
    Samsung(500), 
    Nokia(300), 
    Motorola(400);

    int price;

    Mobile(int price)
    {
        this.price = price;
    }

    int getPrice()
    {
        return price;
    }
}
EnumDemo.java
public class EnumDemo
{
    public static void main(String args[])
    {
        System.out.println("Mobile Phone List:");
        System.out.println("-------------------");
        
        Mobile[] mobileArray = Mobile.values();
        
        for (Mobile mobile : mobileArray)
        {
            System.out.println(mobile + " costs " + mobile.getPrice()
                    + " dollars");
        }
        System.out.println("-------------------");
        
        Mobile mobile = Mobile.Motorola;
        /*
         * Returns the name of this enum constant, exactly
         * as declared in its enum declaration.
         */
        
        String mobileName = mobile.name();      
        System.out.println("\nMobileName = " + mobileName);

    }
}
Output
Mobile Phone List:
-------------------
Samsung costs 500 dollars
Nokia costs 300 dollars
Motorola costs 400 dollars
-------------------

MobileName = Motorola
Click the below link to download the code:

CLICK HERE

No comments:

Post a Comment