1

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...

Jaimin Modi
  • 1,530
  • 4
  • 20
  • 72

1 Answers1

3

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
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 1
    Yeah it's all about : On the other hand, "clean code" tells us to avoid redundancy in our code. Got it. Thanks. – Jaimin Modi Aug 12 '19 at 08:51
  • @JaiminModi Exactly. That is my main point. And please note the update I just made ;-) – GhostCat Aug 12 '19 at 08:52
  • Got it. by default all these fields inside interface is static and final. Is it public by default or not ? little phd here ;) – Jaimin Modi Aug 12 '19 at 08:53
  • 1
    Depends what you mean by redundant. It's *technically* redundant in that the compiler doesn't care whether it's present or not. But that alone should not define whether or you write something more than the bare minimum. The compiler also doesn't care whether you use generics or not. It will compile and run if you rely solely on raw types. But of course we add them anyway because they are useful and help reduce bugs. We should be pragmatic about these things, not dogmatic. – Michael Aug 12 '19 at 09:02
  • @Michael That means It's better that we write static and final keywords while declaring variables in interface..? Because it's useful and just technically redundant.. – Jaimin Modi Aug 12 '19 at 09:05
  • 1
    @JaiminModi That's an opinion. JetBrains (who make IntelliJ) have decided that we should not. It's potentially a useful indicator for people who didn't that the default behaviour is different (like yourself) or to remind people who have forgotten. I would take a neutral stance and say that it's okay to include it, but I wouldn't do so myself. – Michael Aug 12 '19 at 09:09
  • @Michael Looking crystal clear now. Thanks. – Jaimin Modi Aug 12 '19 at 09:51