Search

Sunday, May 23, 2021

Java interface variable

 

Java interface variable

Java interface variable. If you want to get knowledge and clear understanding about variables in Java interface. Then its a best place for you, here i will teach you in detail about Java interface variables with very easy to understand examples.

 

Java interface variables

We can have variables in Java interfaces. But we have some conditions for those variables.

First that they should be public. Because interfaces are implemented by the classes, so accessibility should be public for the classes.

Second they should be static. Because interfaces in Java cannot be instantiated and as interfaces cannot have any object, we should make them static so that they can be accessed with the interface name like Interfacename.NameOfVariable

Third they should be final. This is because if multiple classes implementing same interface try to change the value of variable present in interface can create conflict. So its better to make them final to avoid any conflict because final will help only one-time initialization for the variable.

It is important to know that we can skip public static final with interface variables. If we skip them, Java will automatically make them public static and final.


Example Program

interface A

{

int x=1;

public int x = 1;

public static final int x = 1;

static int x = 1;

final int x = 1;

}


All statements have same meaning, but following statement will give error


Interface B

{

int x;

}


Because, we need to initialized the variable inside an interface. If a class implementing an interface try to change value of the interface variable, Java will generate an error because interface variables are final variable.

It is important to note that two different interface can have same variable name and any class who is implementing both interface can differentiate those variables using their interface names


For Example

interface First

{

public static final int a = 1;

}

interface Second

{

public static final int a = 2;

}

class Test implement First,Second

{

public static void main (String ar[ ])

                {

                System.out.println(First.a);

                Syste.out.println(Second.a);

                }

}


As we have same variable names in both interfaces, so to access them, we have to use interface name and after that variable name to avoid any conflicts.


No comments:

Post a Comment