Default and Static Methods in Java
Default Methods
Default methods enable you to add new functionality to the interfaces of your libraries and ensure binary compatibility with code written for older versions of those interfaces.
interface MathOperations {
public int multiply(int x, int y);
public int add(int x, int y);
public int square(int x);
public default void displayResult(int x) {
System.out.println("The result is : " + x);
}
}
Static Methods
A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods. A static method called without creating the object of the class.
This makes it easier for you to organize helper methods in your libraries; you can keep static methods specific to an interface in the same interface rather than in a separate class.
package com.javacodestuffs.staicmethod.example;
public class Calculator {
public static int multiply(int a, int b) {
return a * b;
}
static int add(int a, int b) {
return a + b;
}
public static void main(String args[]) {
Calculator calc = new Calculator();
int sum = calc.add(123, 51);
int product = Calculator.multiply(51, 123);
System.out.println("Product of numbers is : " + product);
System.out.println("Sum of numbers is : " + sum);
}
}
$javac com/javacodestuffs/staicmethod/example/Calculator.java
$java -Xmx128M -Xms16M com/javacodestuffs/staicmethod/example/Calculator
Product of numbers is : 6273
Sum of numbers is : 174
In this article, we have seen the Default and Static Methods in Java with examples.
0 Comments
Post a Comment