Java Programming

Dhaval Pujara

Dhaval Pujara

@dhaval-pujara-LGoZAW Oct 25, 2024
enum a cute data type in java to declare our own data type values

Why It Can't Be declared inside the Method ..................Why we Have to declare that inside the class

Replies

Welcome, guest

Join CrazyEngineers to reply, ask questions, and participate in conversations.

CrazyEngineers powered by Jatra Community Platform

  • Ankita Katdare

    Ankita Katdare

    @abrakadabra Sep 15, 2013

    Hi @#-Link-Snipped-#
    We take it that you are new to java programming. But you can find the answers to these questions in reference books.
    Answering your query, the reason behind enum's non-ability to be declared inside a method is that enums are always static entities. What this means is that you must be able to access an enum from anywhere in your code, without involving the invocation of any code block (such as a method.)
    Isn't that the whole purpose behind declaring the cute enum keyword? 😀

    If an enum is defined inside a class, it becomes a static member of the class, and you can access it like any static member of the class such as static member classes of the class, as long as the class is accessible from your code.
    If enums were defined inside methods, then they wouldn't be static anymore. You would actually need to invoke the method in order to instantiate the enum.

    You should also keep in mind that - You can mark an enum which is declared inside a class as private or protected, so you must observe the access restrictions like for any other class member.
  • Dhaval Pujara

    Dhaval Pujara

    @dhaval-pujara-LGoZAW Sep 15, 2013

    okk thanks