- 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
- Related Articles
- How to write a class inside an interface in Java?
- How to declare a class and an interface in JShell in Java 9?
- Can we define an interface inside a Java class?
- Can we define a class inside a Java interface?
- How to declare a class in Java?
- Can we declare an interface with in another interface in java?
- Can we declare an interface as final in java?
- How do you declare an interface in C++?
- How to implement an interface using an anonymous inner class in Java?
- Can we define constructor inside an interface in java?
- Can we declare the method of an Interface final in java?
- How to access a derived class member variable by an interface object in Java?
- How to declare member function in C# interface?
- How to declare a variable inside a procedure in MySQL?
- Can we define an enum inside a class in Java?
