MY mENU


Thursday 9 February 2012

static variables in Interface


Interfaces have static keyword implicitly but only for variables e.g.
interface Abc
{
int a = 5;
}

then you can call this variable in static way like Abc.a and the variables in interface are implicitly final also. You can't change the value of variable declared in interface.

The methods declared in interface are not static. They are implicitly abstract and the sub-class must implement all the methods of Interface or the sub-class should also be abstract class if it is not implement the methods of Interface.


To access the instance variable, we have to create the instance of a class. Only then we can access the instance members of a class.

But in the case of interface, we can't create the instance of an Interface. Interface don't have any constructors to create the instance. But we can only declare variable of Interface type. So we can't access the instance variable if we can declare a non-static (instance) variable in interface.

That's why the variables in Interface are implicitly static variables.

But the question can arise in your mind that we can't able to create the instance of an Abstract class also. But we can declare the instance variable in an Abstract class.

The reason behind it is that we also not able to create the instance of an Abstract class directly, but an Abstract class can have constructor and this constructor will be called when we create the object of the sub-class. So Abstract class can have instance variables and we can call them using the object of sub-class.


No comments:

Post a Comment