Java define interface in interface

Defining an Interface

An interface declaration consists of modifiers, the keyword interface , the interface name, a comma-separated list of parent interfaces (if any), and the interface body. For example:

public interface GroupedInterface extends Interface1, Interface2, Interface3 < // constant declarations // base of natural logarithms double E = 2.718282; // method signatures void doSomething (int i, double x); int doSomethingElse(String s); >

The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, then your interface is accessible only to classes defined in the same package as the interface.

An interface can extend other interfaces, just as a class subclass or extend another class. However, whereas a class can extend only one other class, an interface can extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends.

Читайте также:  Python csv dictreader to dict

The Interface Body

The interface body can contain abstract methods, default methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation). Default methods are defined with the default modifier, and static methods with the static keyword. All abstract, default, and static methods in an interface are implicitly public , so you can omit the public modifier.

In addition, an interface can contain constant declarations. All constant values defined in an interface are implicitly public , static , and final . Once again, you can omit these modifiers.

Источник

Nested Interfaces in Java

Similar to nested classes we have nested interfaces in java. An interface defined inside another interface or class is known as nested interface. Nested interface is also known as inner interfaces or member interfaces. Nested interfaces are generally used to group related interfaces. The syntax of declaring nested interface is :

interface OuterInterfaceName < interface InnerInterfaceName < // constant declarations // Method declarations > > Example : interface MyInterface < interface MyInnerInterface < int void print(); > >

Nested interface can be defined anywhere inside outer interface or class. Some of the key points about nested interfaces are :

  • Nested interfaces are static by default, irrespective of you declare it static or not.
  • Nested interfaces are accessed using outer interface or class name.
  • Nested interfaces declared inside a class can have any access modifier, while nested interfaces declared inside another interfaces are public by default.
  • Classes implementing inner interface are required to implement only inner interface methods, not outer interface methods.
  • Classes implementing outer interface are required to implement only outer interface methods, not inner interface methods.
Читайте также:  Питон цикл while синтаксис

Does java compiler creates separate .class file for nested interfaces ?

Yes, Java compiler creates separate .class file for nested interfaces, whose name is made with combination of outer and inner interface name with $ sign in between. For example the name of .class file in above declaration would be MyInterface$MyInnerInterface.class .

Nested interface program in Java

interface MyInterface < void calculateArea(); interface MyInnerInterface < int void print(); > > class NestedInterface implements MyInterface.MyInnerInterface < public void print() < System.out.println("Print method of nested interface"); > public static void main(String args []) < NestedInterface obj = new NestedInterface(); obj.print(); System.out.println(obj.id); > >

Print method of nested interface
20

As mentioned above nested interface can be declared inside a class as well. Class implementing such interface needs to define all the methods of that nested interface. The program below demonstrates the nested interface declared inside a class.

Java program of nested interface declared inside a class

class OuterClass < interface MyInnerInterface < int void print(); > > class NestedInterfaceDemo implements OuterClass.MyInnerInterface < public void print() < System.out.println("Print method of nested interface"); > public static void main(String args []) < NestedInterfaceDemo obj = new NestedInterfaceDemo(); obj.print(); System.out.println(obj.id); // Assigning the object into nested interface type OuterClass.MyInnerInterface obj2 = new NestedInterfaceDemo(); obj2.print(); > >

Print method of nested interface
20
Print method of nested interface

The object of implementing class can also be assigned in to nested interface type, as in above program obj2 is an object of NestedInterfaceDemo class but assigned into MyInnerInterface type.

As mentioned above class implementing an outer interface are not required to implement the inner or nested interface methods. The program below demonstrates the same.

interface MyInterface < void calculateArea(); interface MyInnerInterface < int void print(); > > class OuterInterfaceTest implements MyInterface < public void calculateArea() < System.out.println("Calculate area inside this method"); > public static void main(String args []) < OuterInterfaceTest obj = new OuterInterfaceTest(); obj.calculateArea(); > >

Calculate area inside this method

Why do we use nested interface in java

There are couple of reasons for using nested interfaces in java :

  • Nesting of interfaces is a way of logically grouping interfaces which are related or used at one place only.
  • Nesting of interfaces helps to write more readable and maintainable code.
  • It also increases encapsulation.

One example of nested interface in java library is java.util.Map.Entry interface defined inside java.util.Map interface. We access it as Map.Entry , as it’s a nested interface.

  • An interface or class can have any number of inner interfaces inside it.
  • Inner interface can extend it’s outer interface.
  • Inner and outer interfaces can have method and variables with same name.
  • Nested interfaces can also have default and static methods from java 8 onward.
  • An inner class defined inside an interface can implement the interface.
  • Nesting of interfaces can be done any number of times. As a good practice you should avoid doing nesting more than once.

Источник

Can we declare an interface with in another interface 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 declaring interfaces within another interface, these are known as nested interfaces.

While implementing you need to refer to the nested interface as outerInterface.nestedInterface.

Example

In the following Java example, we have an interface with name Cars4U_Services which contains two nested interfaces: CarRentalServices and, CarSales with two abstract methods each.

From a class we are implementing the two nested interfaces and providing body for all the four abstract methods.

interface Cars4U_Services < interface CarRentalServices < public abstract void lendCar(); public abstract void collectCar(); >interface CarSales < public abstract void buyOldCars(); public abstract void sellOldCars(); >> public class Cars4U implements Cars4U_Services.CarRentalServices, Cars4U_Services.CarSales < public void buyOldCars() < System.out.println("We will buy old cars"); >public void sellOldCars() < System.out.println("We will sell old cars"); >public void lendCar() < System.out.println("We will lend cars for rent"); >public void collectCar() < System.out.println("Collect issued cars"); >public static void main(String args[]) < Cars4U obj = new Cars4U(); obj.buyOldCars(); obj.sellOldCars(); obj.lendCar(); >>

Output

We will buy old cars We will sell old cars We will lend cars for rent

Источник

Nested Interface in Java | Example Program

Scientech Easy

When an interface as a static member is declared inside a class or another interface, it is called nested interface in java or member interface.

Nested interface must be declared as public inside another interface. The nested interface can be declared in the following general form.

1. Interface inside another Interface

The general syntax to define an interface inside another interface in Java is as follows:

In the preceding syntax, the interface Inner is defined as public inside another interface Outer. So it is known as nested interface.

Now a class can implement nested interface Inner by using the following below statement.

class Hello implements Outer.Inner < // Body of class >

In above example, Outer represents a top-level interface in which interface Inner is a member. Class Hello implements nested interface by specifying “implements Outer.Inner”.

Let’s take another example of declaring inner interface inside outer interface.

Interface Entry is defined inside the interface Map. Thus, Entry is a nested interface of Map and it can be accessed by calling Map.Entry. A map is a group of key-value pairs (also known as entries).

2. Interface inside Class

The general syntax to define an interface inside a class in java is as follows:

Now a class can implement member interface Inner by using following statement:

Class A implements Outer.Inner < // Body of class. >

In this example, Outer represents a class in which interface Inner is a member.

Points to Remember for Java Nested Interface

There are some important points regarding in nested interface which have to keep in mind you. They are as follows:

1. Every inner interface or class is always implicitly public and static whether we are declaring or not.

Nested interface in Java

2. If you declare inner interface inside a class then it can have any access modifiers.

3. When you implement an outer interface, you are not required to provide implementation for inner interface. We can directly implement the outer interface.

4. Similarly, when you implement an inner interface, you are not required to provide implementation for outer interface because inner interface is always public and static. Hence, we can implement inner interface directly without implementing outer interface.

Java Nested Interface Example Program

Let’s create a program where we will declare an interface inside another interface and will learn how to access outer and nested interface.

package nestedInterfaceProgram; public interface Outer < void m1(); // Outer interface contains m1() method. interface Inner < void m2(); // Inner interface contains m2() method. >> // Implementation of top-level interface: public class MyClass1 implements Outer < public void m1() < System.out.println("Hello"); >> // Implementation of inner interface: public class MyClass2 implements Outer.Inner < public void m2() < System.out.println("Java"); >> public class Test < public static void main(String[] args) < MyClass1 c1 = new MyClass1(); // Creating object of class MyClass1. c1.m1(); // Calling m1() method. MyClass2 c2 = new MyClass2(); // Creating object of class MyClass2. c2.m2(); // Calling m2() method. >>

As you can see output of the above program that we can implement independently both Outer and Inner interfaces.

Internal code Generated by the java compiler for nested interface

The java compiler internally adds public and static with nested interface as shown in below coding:

public static interface Outer$Inner

Interface inside Class Example Program

If you require multiple implementations of an interface and all these implementations are related to a particular class, It is highly recommended to define an interface within a class. Let’s understand it by an example program.

package nestedInterfaceProgram; public class VehicleTypes < interface Vehicle < public int getNoOfWheels(); >> public class Bus implements VehicleTypes.Vehicle < public int getNoOfWheels() < return 6; >> public class Car implements VehicleTypes.Vehicle < public int getNoOfWheels() < return 4; >> public class Bike implements VehicleTypes.Vehicle < public int getNoOfWheels() < return 2; >> public class VehicleTest < public static void main(String[] args) < Bus b = new Bus(); System.out.println(b.getNoOfWheels()); Car c = new Car(); System.out.println(c.getNoOfWheels()); Bike bk = new Bike(); System.out.println(bk.getNoOfWheels()); >>

As you can see in above program, within a class, an interface has multiple implementations provided by multiple classes and all these implementations are related to a particular class.

The access modifier for inner interface in the preceding program is default. You can also assign public, protected, or private.

Let’s take another example program in which we declare protected for nested interface and see what happens?

package nestedInterfaceProgram; public class Cube < protected interface Number < public void calculateCube(int n); >> public class Five implements Cube.Number < public void calculateCube(int n) < int cubeN = n * n * n; System.out.println("Cube of 5: " +cubeN); >> public class Ten implements Cube.Number < public void calculateCube(int n) < int cubeN = n * n * n; System.out.println("Cube of 10: " +cubeN); >> public class CubeTest < public static void main(String[] args) < Five f = new Five(); f.calculateCube(5); Ten t = new Ten(); t.calculateCube(10); >>
Output: Cube of 5: 125 Cube of 10: 1000

In this particular example program, if we change the access modifier to private, we get compile-time error because a derived class tries to access it.

Can we declare Class inside Interface?

If the functionality of class is closely associated with interface functionality, it is highly recommended to declare a class inside the interface. In this case, the class will act like inner class to interface.

Let’s understand it with the best example program.

In the preceding example program, EmailDetails is required only for YahooMail and we can not use it anywhere else i.e, the functionality of class EmailDetails is associated with an interface YahooMail. Hence, we have declared EmailDetails class inside YahooMail interface.

FAQs on Nested Interface

1. What is nested interface in Java?

2. Can we have interface inside interface in Java?

3. Can a class have an interface?

Hope this tutorial has covered almost all important points related to Java nested interface with example programs. I hope that you will have understood the basic concept and enjoyed this tutorial.

In the next tutorial, we will learn about the difference between abstract class and interface in Java with the help of example.
Thanks for reading.
Next ⇒ Difference between Abstract class and Interface in Java ⇐ PrevNext ⇒

Источник

Оцените статью