• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Private Methods in Interfaces Java 9

May 23, 2017 by javainterviewpoint 2 Comments

In Java 9, Private Methods in Interfaces has been introduced. This enables code sharing between non-abstract methods in an interface. In this article apart from understanding the Private Method in Interface, we will learn how the Interface has evolved in different versions of Java.

Java 7 (Or) Earlier Interface:

In Java 7 or earlier versions of Java, Interface is very simple they can have only abstract methods and constants. Since the methods are abstract it cannot have implementations. If we want to have both abstract and non-abstract methods then there is no other go we need to for abstract class only.

public interface Calculator
{
    public void add(int a, int b);
    public void subtract(int a, int b);
    public void multiply(int a, int b);
    public void divide(int a, int b);
}

Here in our Calculator interface we have four unimplemented abstract methods add (), subtract (), multiply (), divide (). The class which implements the Calculator interface will provide the body for the abstract methods (add (), subtract (), multiply (), divide ()).

Java 8 Interface:

Later in Java 8, Default Methods and Static methods has been added to the interface, which helped us to have an implementation for a method in an interface all we need to do is just add “default” keyword in front of the method. In Java 8 along with abstract methods and constants, it has default method and static method.

Now our Calculator interface can be re-written like below (with body)

package com.javainterviewpoint;

import java.util.Scanner;

public interface Calculator
{
    public default void add()
    {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter Number1 : ");
        int a = scanner.nextInt();

        System.out.println("Enter Number2 : ");
        int b = scanner.nextInt();

        System.out.println(a + b);
    }
    public default void subtract()
    {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter Number1 : ");
        int a = scanner.nextInt();

        System.out.println("Enter Number2 : ");
        int b = scanner.nextInt();

        System.out.println(a - b);
    }
    public default void multiply()
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Number1 : ");
        int a = scanner.nextInt();

        System.out.println("Enter Number2 : ");
        int b = scanner.nextInt();

        System.out.println(a * b);
    }
    public default void divide()
    {
        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter Number1 : ");
        int a = scanner.nextInt();

        System.out.println("Enter Number2 : ");
        int b = scanner.nextInt();

        System.out.println(a / b);
    }
}

We have provided the implementations for all the methods in the above code, but when we look into the code we can understand that we have a small issue here. We have some redundant code such as Creating a Scanner object and Reading both the numbers which can be moved to a common method but as an API developer we never want to expose the logic to the consumer. There is no solution for this in Java 8, which is the main reason for the introduction of Private Methods in Java 9.

Java 9 Interface:

In Java 9, Private Methods has been introduced which lets us share the code between the other public methods. Now we can re-write the code like below

package com.javainterviewpoint;

import java.util.Scanner;

public interface Calculator
{
    public default void add()
    {
      calc("add");
    }
    public default void subtract()
    {
        calc("subtract");
    }
    public default void multiply()
    {
        calc("multiply");
    }
    public default void divide()
    {
        calc("divide");
    }
    
    private default void calc(String operation)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Number1 : ");
        int a = scanner.nextInt();
        
        System.out.println("Enter Number2 : ");
        int b = scanner.nextInt();
        
        if (operation.equals("add"))
        {
            System.out.println(a+b);
        }
        else  if (operation.equals("subtract"))
        {
            System.out.println(a-b);
        }
        else  if (operation.equals("multiply"))
        {
            System.out.println(a*b);
        }
        else
        {
            System.out.println(a/b);
        }
    }
}

Now we have moved the redundant code a single private method that is not visible to the consumer as well. The Private Method must have a body (must be implemented) and have you cannot have abstract specifier for the Private Method.

Interfaces in Java 9 will now have abstract methods, constants, default methods, static methods, private methods and private static methods. Happy Learning 🙂

Filed Under: Core Java, Java Tagged With: Private Methods in Interfaces

Comments

  1. Vinayak A says

    September 20, 2017 at 5:14 pm

    Hello Sir,

    Thanks for sharing such a nice post.

    Reply
  2. Pumpkin says

    November 14, 2017 at 10:07 pm

    Really helpful article..!!

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·