• Post Reply Bookmark Topic Watch Topic
  • New Topic

Object Created inside switch  RSS feed

 
Dan Dowe
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Code Ranch peeps;

I'm very new to Java and this is my very first post within the coderanch and was wondering if any of you could assist me with the issue I'm encountering,

To explain my issue I have create as short example which contains two classes Cat and Dog followed by a switch statement in the main method.

Class Cat



Class Dog




Main Method




My Issue is that after creating the objects within the switch statement, I am not able to access them within my main method - is there a way to return the objects back to the main method once created within the switch ? or am I going about this to wrong way ?

would really appreciate some help








 
fred rosenberger
lowercase baba
Bartender
Posts: 12563
49
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you need to declare the reference outside the switch so it doesn't fall out of scope.

you probably want both Dog and Cat to extend Animal or Pet or Mammal or something...so you'd then do this:

 
Dan Dowe
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brilliant, thank you for your time

 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!