0% found this document useful (0 votes)
1 views13 pages

Module3 Interface-1

An interface in Java is an abstract type that defines a set of behaviors for classes to implement, promoting abstraction and multiple inheritance. Interfaces can contain static constants and abstract methods, and they must be implemented fully by any class that uses them. Additionally, interfaces can be nested within classes or other interfaces, and Java 8 introduced default and static methods to enhance their functionality without breaking existing implementations.

Uploaded by

namithad115
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
1 views13 pages

Module3 Interface-1

An interface in Java is an abstract type that defines a set of behaviors for classes to implement, promoting abstraction and multiple inheritance. Interfaces can contain static constants and abstract methods, and they must be implemented fully by any class that uses them. Additionally, interfaces can be nested within classes or other interfaces, and Java 8 introduced default and static methods to enhance their functionality without breaking existing implementations.

Uploaded by

namithad115
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Interfaces Defining an Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. «The interface in Java is a mechanism to achieve abstraction. + By default, variables in an interface are public, static, and final. + Itis used to achieve abstraction and multiple inheritances in Java. + It is also used to achieve loose coupling. + In other words, interfaces primarily define methods that other classes must implement. ‘+ An interface in Java defines a set of behaviours that a class can implement, usually representing an IS-A relationship, but not always in every scenario. Example: import [Link]."; interface testInterface ( // public, static and final final int a= 10; // public and abstract void display(); } Class implementing interface class TestClass implements testInterface { // Implementing the capabilities of “Interface public void display(){ [Link]("Demo"); } th class A { public static void main(String{| args) { TestClass t = new TestClass(); tdisplay(); ‘[Link](t.a); } © scanned wt OREN Scanner Note: In Java, the abstract keyword applies only to classes and methods, indicating that they cannot be instantiated directly and must be implemented. When we decide on a type of entity by its behaviour and not via attribute we should define it as an interface. Syntax: interface { 1/ declare constant fields / declare methods that abstract M by default. } © To declare an interface, use the interface keyword. It is used to provide total abstraction. That means all the methods in an interface are declared with an empty body and all fields are public, static, and final by default. A class that implements an interface must implement all the methods declared in the interface. To implement the interface, use the implements keyword. Relationship Between Class and Interface A class can extend another class, and similarly, an interface can extend another interface. However, only a class can implement an interface, and the reverse (an interface implementing a class) is not allowed. Implementing Interfaces: To implement an interface, we use the keyword implements Example: (/ Define an interface interface Movable ( void move): } (Implement the interface class Car implements Movable { public void move() { ‘[Link] printIn("Car is moving. © scanned wt OREN Scanner (Main class Public class InterfaceExample2 ( public static void main(Stringl] args) { Movable car = new Car(); // Create a Car object [Link](); // Call the move method } Multiple Inheritance in Java Using Interface Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes. But we can use multiple inheritances in Java using Interface. Let us check this with an example. Multiple inheritance in Java cam) [ome] [ee] oe ] Examph impor [Link].* 1/ Add interface interface Add{ int add¢int aint b); } 1/ Sub interface interface Sub( int sub(int [Link] b); J 1 Calculator class implementing W Add and Sub class Cal implements Add , Sub { 1 Method to add two numbers public int add(int a,int 6){ return a+b; © seamed witsonen scanner 1 Method to sub two numbers public int subGint int b){ return a-b; J J class Caleex{ 1/ Main Method public static void main (String{] args) ( instance of Cal class Cal x = new Cal(); ‘System out printin("Addition : " + [Link](2,1)); ‘System. out printin(’Substraction : * + [Link](2,1)); 1 Nested Interface in Java: ‘We can declare interfaces as members of a class or another interface. Such an interface is (led a member interface or nested interface. Interfaces declared outside any class can have only public and default access specifiers. In Java, nested interfaces (interfaces declared inside a class or another interface) can be declared with the public, protected, package-private (default), or private access specifiers. + Annested interface can be declared public, protected, package-private (default), or private. + A top-level interface (not nested) can only be declared as public or package-private (default) + Itcannot be declared as protected or private. Syntax: interface i_first{ interface i_second{ } } When implementing a nested interface, we refer to it as i_firs of the interface in which the interface is nested and i_second is the interface’s name. (OF scanned wth oneN Scanner 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 OuterlaterfaceName { interface InnerInterfaceName { J/ constant declarations // Method declarations Example : interface Myinterface { interface MyInnerInterface { int id = 20; void print(); My 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 iterfaces declared inside another terfaces 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, © scanned wt OREN Scanner Nested interface program in Java interface MyInterface { void calculatearea(); interface MyInnerInterface { int id = 205 void print(); class Nestedinterface inplenents [Link] { public void print() { [Link](“Print method of nested interface"); + public static void main(String args []) { NestedInterface obj = new NestedInterface(); obj .print(); [Link].print1n([Link]); Output: Print method of nested interface 20 ‘As mentioned above neste erface 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. © seamed witsonen scanner class Outerclass { interface MyInnerInterface { int id = 20; void print(); class NestedInterfaceDemo implements [Link] { public void print() { [Link]("Print method of nested interface"); ? public static void main(String args []) { NestedInterfaceDemo obj = new NestedInterfaceDemo(); [Link](); [Link].print1n([Link]); // Assigning the object into nested interface type [Link] obj2 = new NestedInterfaceDemo(); [Link]()s 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 MylnnerInterface 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 calculatesrea(); interface MyInnerInterface { int 4d = 205 void print()s » class OuterInterfaceTest implenents MyInterface { public void caleulatesrea() { [Link](“Calculate area inside this method"); ) public static void main(String args []) { OuterInterfaceTest obj = new OuterInterfaceTest(); [Link](); > © seamed witsonen scanner ‘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 NOTE: > > > ¥ v An interface or class can have any number of inner interfaces inside it. Tnner 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. Applying Interfaces ‘The interface is a powerful tool. The same interface can be used by different classes for some method. Then this method can be implemented by each class in its own way. Thus same interface can provide variety of implementation. The selection of different implementations is done at the run time, Following is a simple Java program which illustrates this idea. Step 1: Write a simple interface as follows Java Program [[Link]] interface interface! void MyMsg(String s); © scanned wt OREN Scanner Step 2: Write a simple Java Program having two classes having their own implementation of MyMsg method. Java Program|[[Link]] import [Link].*; import [Link].*; class Class! implements interface! { private String s; public void MyMsg(String s) { [Link]("Hello "+s); } } class Class2 implements interface { private String s; public void MyMsg(String s) { [Link]("Hello "+s); } } class Test { public static void main(String[] args) { interface! inter; Class1 objl=new Class! (); Class2 obj2=new Class2(); inter=obj1; inter. MyMsg(""User!"); inter=obj2; [Link]("User2"); } } Step 3: Execute the program. Javac test java Java test Hello Userl Hello User 2 © seamed witsonen scanner Variables in Interfaces «Every interface variable is always public, static, final whether we are declaring or not. + If any variable in an interface is defined without public, stat and final keywords the compiler automatically add the same. Ex: Interface int] { Int X =10; e: to make this variable available for every implementation cl ss. Without existing object also implementation ct n access this variable. |: Implementation class can access this variable but cannot modify, Hence inside the interface the following declaration are valid and equal. * Interface variables are public, static and final we Cannot declare with following modifiers. Private Protected Transient Volatile © scanned wth OREN Scanner > Inside Implementation classes we can access interface variables but we can't modify their values. In Java interfaces, both default and static methods allow for adding implementations to interfaces without breaking backward compatibility with existing implementations, but they differ in how they are invoked and their purpose Default Methods: Purpose: Provide a default implementation for methods in an interfac implementing the interface to inherit that implementation or override it. allowing classes Invocation: Default instance methods, interface MyInterface { void abstractMethod(); // Abstract method default void defaultMethod() { [Link](""Default is thods are invoked on instances of the implementing class, just like regular Jementati Static Method: Purpose: Define utility methods that belong to the interface itself, not to any instance of the interface. Invocation: Static methods are invoked using the interface name, not an instance of the implementing class. interface MyInterface { void abstractMethod); static void statieMethod( { System. [Link]("St implementation"); © scanned wth OREN Scanner Default Methods: Default and static methods were introduced in Java 8 to enhance the functionality of interfaces. Default methods provide a way to add new methods to an interface without breaking existing implementations. + They are declared using the default keyword and include a method body, offering a default implementation. ‘Implementing classes can choose to override default methods or inherit the default implementation. Example: interface Mylnterface { void abstractMethod(); default void defaultMethod() ‘[Link]("Default method implementation"); } } class MyClass implements Mylnterface { @ Override public void abstractMethod() { ‘[Link] printIn("Abstract method implementation"); J // Inherits defaultMethod() from MyInterface } public class Main { public static void main(String[] args) { MyClass obj [Link](; // Output: Abstract method implementation new MyClass(); [Link](); // Output: Default method implementation } © scanned wt OREN Scanner Static Methods: * Static methods in interfaces are similar to static methods in classes. «They are declared using the static keyword and belong to the interface itself, not to instances of implementing classes. * Static methods are called using the interface name and are often used for utility or helper functions related to the interface. Example: interface MyInterface { statie void staticMethod() { ‘[Link]("Static method implementation"); } J public class Main { public static void main(String[] args) { [Link]; // Output: Static method implementation } } © scanned wt OREN Scanner

You might also like