Can we create non static variables in an interface using java?


Interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.

Since all the methods are abstract you cannot instantiate it. To use it, you need to implement this interface using a class and provide body to all the abstract methods int it.

Non static variables in an interface

No you cannot have non-static variables in an interface. By default,

  • All the members (methods and fields) of an interface are public

  • All the methods in an interface are public and abstract (except static and default).

  • All the fields of an interface are public, static and, final by default.

If you declare/define fields without public or, static or, final or, all the three modifiers. Java compiler places them on your behalf.

Example

In the following Java program, we are having a filed without public or, static or, final modifiers.

public interface MyInterface{
   int num = 40;
   void demo();
}

If you compile this using the javac command as shown below −

c:\Examples>javac MyInterface.java

it gets compiled without errors. But, if you verify the interface after compilation using the javap command as shown below −

c:\Examples>javap MyInterface
Compiled from "MyInterface.java"
public interface MyInterface {
   public static final int num;
   public abstract void demo();
}

You can observe that the compiler has placed the public, static and, final modifiers before the field on behalf of you.

Updated on: 29-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements