• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

enum

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi

please see the below code

class staticdemo
{
String name="shenba";
}

class statictest
{
static staticdemo obj;
public static void main(String arg[])
{
System.out.println(obj.name);
}
}

in the statictest class i create reference obj of type staticdemo.but the obj is not referring any object. so during when i try to access the name variable using obj it throws null pointer exception.

but in the case of enum the same thing is not giving any issues.

enum animal
{
dog("woof"), cat("meow");
String sound;
animal(String s)
{
sound=s;
}
public String getSound()
{
return sound;
}

};

class enumdemo1
{
static animal a;
public static void main(String arg[])
{
System.out.println(a.dog.sound);
System.out.println(a.dog.getSound());

System.out.println(a.cat.sound);
System.out.println(a.cat.getSound());
}
}


static animal a;

In the above code value for a is not assigned.ie some thing like animal.dog is not assigned.but the code a.dog.sound is not giveing any exception during run time.

enum also a special type of class only right? then why different behaviour in enum?
 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
You're trying to refer to an instance member (name) of class staticdemo without getting an instance of it first. Only static members can be called without an instance of a class. With the enum, calling a.dog will call the constructor for the DOG constant which in turn assigns the String value to name. You never call 'new EnumName.Const' - if a constructor exists it is implicitly called when you say EnumName.CONST

Hope that helps... and is correct...!
 
Today's lesson is that you can't wear a jetpack AND a cape. I should have read this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic