Syntax error What happens if we does not initialize variables of an interface in java?

What happens if we does not initialize variables of an interface in java?



In Java final is the access modifier which can be used with a filed class and a method.

  • When a method if final it cannot be overridden.
  • When a variable is final its value cannot be modified further.
  • When a class is finale it cannot be extended.

Declaring final variable without initialization

If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don’t you will get a compilation error.

Example

In the following java program, we a have an interface with a public, static, final variable with name num and, a public, abstract method with name demo.

public interface MyInterface {
   public static final int num;
   public abstract void demo();
}

Compile time error

On compiling, the above program generates the following error.

Output

MyInterface.java:2: error: = expected
   public static final int num;
^
1 error
Updated on: 2020-06-29T14:16:56+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements