- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.