How to implement Static methods in interface concept in java8???
The word “Static” is applicable for the interface. It does not be an instance of the class which implements the interface.
Why static method???
- · Scope of the static methods is visible within interface.
- · It belongs to interface only. So, utility methods are declared as static methods.
Simple program to implement static methods in interface:
This
program creates an interface with a static method “staticMd()” to print the
static method message. Even though, a class is declared to implement the
interface, the method belongs to the interface only.
//Java Program to implement static methods in interface
interface MyInter {
static void
staticMd() {
System.out.println("This is a static method in an interface MyInter");
}
}
public class MyCls implements MyInter {
public static void
main(String[] args) {
MyInter.staticMd(); // Function call
}
}
Save this file as “MyCls.java”.
Compile the program in command prompt.
C:\raji\blog>javac MyCls.java
Execute the program as follows. You will get this output.
C:\raji\blog>java MyCls
This is a static method in an interface MyInter.
Java Program to implement Odd/Even number checking using
static methods in interface:
This java
program has following steps to implement the concept.
- Create an interface “MyInter1”.
- Inside the interface, implement the static method as “static void staticOddEven(int a)”.
Where,
static – keyword.
void – return type.(It doesn’t return anything)
staticOddEven – this is the static function name.
int a – input of a function as integer.
- This function checks the given number is odd or even and print it.
- Create a class “MyCls1” to implement the interface “MyInter1”.
- Inside it,create a main function.
- Call the static function “MyInter1.staticOddEven(6)”.
// Java Program to implement Odd/Even number checking
using static methods in interface
interface MyInter1 {
static void
staticOddEven(int a) {
if(a%2==0)
System.out.println("The number is a even number");
else
System.out.println("The number is a even number");
}
}
public class MyCls1 implements MyInter1 {
public static void
main(String[] args) {
MyInter1.staticOddEven(6); // static method call
}
}
Compile and run the program to get the output.
C:\raji\blog>javac MyCls1.java
C:\raji\blog>java MyCls1
The number is a even number
These are the ways to implement the static methods in interface concept in java8. Keep Coding!!!!
Comments
Post a Comment