Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an interface hold any instance variables?

Tags:

java

Can an interface hold any instance variables? In my instructor's specs, it says no instance variables are allowed in interface. But I've researched and some say that it can only contain final instance variable. If it can hold a final instance variable, so what role can that variable play at all in an interface?

like image 990
Nikolay Avatar asked Apr 16 '15 06:04

Nikolay


People also ask

Can a interface have instance variables?

No interface cannot have instance variable.

Can Java interface hold variables?

2.1.In an interface, we're allowed to use: constants variables. abstract methods. static methods.

What variables are allowed inside an interface?

The interface contains the static final variables. The variables defined in an interface can not be modified by the class that implements the interface, but it may use as it defined in the interface. 🔔 The variable in an interface is public, static, and final by default.

CAN interface have instances?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete. Still if you try to instantiate an interface, a compile time error will be generated saying “MyInterface is abstract; cannot be instantiated”.


4 Answers

variables declared in interface are by default public, static and final. Since it is static you cannot call it instance variable.

like image 116
Aniket Thakur Avatar answered Oct 22 '22 04:10

Aniket Thakur


  • Variables which declared in interface are by default public, static and final.

  • These are static so you cannot call it as instance variable.

like image 4
Ranjeet Avatar answered Oct 22 '22 04:10

Ranjeet


By default interface variables will always be public static final whether you mention these modifiers or not while defining variables. So, you can never have an instance variable in an interface.

like image 2
user85 Avatar answered Oct 22 '22 02:10

user85


Variables declared in an interface are by default public, static and final by default. So you can use interfaces to define constants.

You can read more about this Here

enter image description here

like image 1
Gihan Saranga Siriwardhana Avatar answered Oct 22 '22 02:10

Gihan Saranga Siriwardhana