Kevan
Kevan

Reputation: 1195

Why you cannot declare member interfaces in a local class?

You cannot declare an interface inside a block like below

public void greetInEnglish() {

        interface HelloThere {
           public void greet();
        }

        class EnglishHelloThere implements HelloThere {
            public void greet() {
                System.out.println("Hello " + name);
            }
        }

        HelloThere myGreeting = new EnglishHelloThere();
        myGreeting.greet();
}

In This Oracle tutorial I got "You cannot declare member interfaces in a local class." because "interfaces are inherently static."

I am eagar to understand this with more rational information, why and how interface are inherently static?

and why above code does not make sense?

Thanks in advance to elloborate!

Upvotes: 6

Views: 1463

Answers (3)

Neeraj Jain
Neeraj Jain

Reputation: 7720

I am eagar to understand this with more rational information, why and how interface are inherently static?

because interfaces are implicitly static, and you can't have non-final statics in an inner class.

Why are they implicitly static?

because that's the way they designed it.

and why above code does not make sense?

because of the above reason ,

Now lets make it simple :

What static means - "not related to a particular instance". So, suppose, a static field of class Foo is a field that does not belong to any Foo instance, but rather belongs to the Foo class itself.

Now think about what an interface is - it's a contract, a list of methods that classes which implement it promise to provide. Another way of thinking about this is that an interface is a set of methods that is "not related to a particular class" - any class can implement it, as long as it provides those methods.

So, if an interface is not related to any particular class, clearly one could not be related to an instance of a class - right?

I also suggest you to study Why static can't be local in Java?

Upvotes: 2

nrainer
nrainer

Reputation: 2633

Your code does not make sense because you define the interface within the body of a method. You can define an interface either at top level or in another class or interface.

You cannot declare an interface inside a block

reference

Upvotes: 0

Anptk
Anptk

Reputation: 1123

Any implementations can change value of fields if they are not defined as final. Then they would become a part of the implementation.An interface is a pure specification without any implementation.

If they are static, then they belong to the interface, and not the object, nor the run-time type of the object.

An interface provide a way for the client to interact with the object. If variables were not public, the clients would not have access to them.

Upvotes: 0

Related Questions