Static and Final Rules of Interface

Jaimin Modi :

What exactly the meaning of instance fields in JAVA ?

As per am knowing in JAVA :

An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.

But, When I have tried as below :

interface TempIn
{
        TakeInput tv=null;
        String name="";
        int temp=0;
        void printT();
}

and it's working. How ? Confused...

GhostCat salutes Monica C. :

Simple: all these fields are static and final by default.

Therefore the java language allows you to write down something that is implicitly given.

In other words: imagine the "compiler" putting down the keywords for you.

But I agree, this is a bit of confusing. And it also turns a bit into a "style" thing. In the early years of Java, a lot of people would add these redundant keywords to their interfaces. On the other hand, "clean code" tells us to avoid redundancy in our code. And nowadays, an IDE like IntelliJ will even give you warnings when using the keywords. So, my recommendation:

  • don't touch old, existing code
  • talk to your team, and decide what makes sense for you, and for new code, follow that agreement

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325710&siteId=1