- 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
How to write/declare an interface inside a class in Java?
An interface in Java is a specification of method prototypes. Whenever you need to guide the programmer or, make a contract specifying how the methods and fields of a type should be you can define an interface.
To create an object of this type you need to implement this interface, provide body for all the abstract methods of the interface and obtain the object of the implementing class.
Nested interfaces
Java allows writing/declaring interfaces within another interface or, within a class these are known as nested interfaces.
Example
In the following Java example, we have a class with name Sample which contains a nested interface named myInterface.
In the class Sample we are defining a nested class named InnerClass and implementing the nested interface.
public class Sample { interface myInterface{ void demo(); } class InnerClass implements myInterface{ public void demo(){ System.out.println("Welcome to Tutorialspoint"); } } public static void main(String args[]){ InnerClass obj = new Sample().new InnerClass(); obj.demo(); } }
Output
Welcome to Tutorialspoint
You can also implement the nested interface using class name as −
Example
class Test { interface myInterface{ void demo(); } } public class Sample implements Test.myInterface{ public void demo(){ System.out.println("Hello welcome to tutorialspoint"); } public static void main(String args[]){ Sample obj = new Sample(); obj.demo(); } }
Output
Hello welcome to tutorialspoint