Open In App

Private Methods in Java 9 Interfaces

Last Updated : 02 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Java 9 onwards, you can include private methods in interfaces. Before Java 9 it was not possible.

Interfaces till Java 7

In Java SE 7 or earlier versions, an interface can have only two things i.e. Constant variables and Abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface.




// Java 7 program to illustrate
// private methods in interfaces
public interface TempI {
    public abstract void method(int n);
}
  
class Temp implements TempI {
    @Override
    public void method(int n)
    {
        if (n % 2 == 0)
            System.out.println("geeksforgeeks");
        else
            System.out.println("GEEKSFORGEEKS");
    }
  
    public static void main(String[] args)
    {
        TempI in1 = new Temp();
        TempI in2 = new Temp();
        in1.method(4);
        in2.method(3);
    }
}


OUTPUT : geeksforgeeks
         GEEKSFORGEEKS

Java 8 Interface Changes

Some new features to interface were introduced in Java 8 i.e. Default methods and Static methods feature. In Java 8, an interface can have only four types:

  1. Constant variables
  2. Abstract methods
  3. Default methods
  4. Static methods

Example




// Java 8 program to illustrate
// static, default and abstract methods in interfaces
public interface TempI {
  
    public abstract void div(int a, int b);
  
public default void
    add(int a, int b)
    {
        System.out.print("Answer by Default method = ");
        System.out.println(a + b);
    }
  
    public static void mul(int a, int b)
    {
        System.out.print("Answer by Static method = ");
        System.out.println(a * b);
    }
}
  
class Temp implements TempI {
  
    @Override
    public void div(int a, int b)
    {
        System.out.print("Answer by Abstract method = ");
        System.out.println(a / b);
    }
  
    public static void main(String[] args)
    {
        TempI in = new Temp();
        in.div(8, 2);
        in.add(3, 1);
        TempI.mul(4, 1);
    }
}


OUTPUT : Answer by Abstract method = 4
         Answer by Default method = 4
         Answer by Static method = 4

Java 9 Interface Changes

Java 9 introduced private methods and private static method in interfaces. In Java 9 and later versions, an interface can have six different things:

  1. Constant variables
  2. Abstract methods
  3. Default methods
  4. Static methods
  5. Private methods
  6. Private Static methods
  7. These private methods will improve code re-usability inside interfaces and will provide choice to expose only our intended methods implementations to users.These methods are only accessible within that interface only and cannot be accessed or inherited from an interface to another interface or class.




    // Java 9 program to illustrate
    // private methods in interfaces
    public interface TempI {
      
        public abstract void mul(int a, int b);
      
    public default void
        add(int a, int b)
        {
    // private method inside default method
            sub(a, b); 
      
     // static method inside other non-static method
            div(a, b);
            System.out.print("Answer by Default method = ");
            System.out.println(a + b);
        }
      
        public static void mod(int a, int b)
        {
            div(a, b); // static method inside other static method
            System.out.print("Answer by Static method = ");
            System.out.println(a % b);
        }
      
        private void sub(int a, int b)
        {
            System.out.print("Answer by Private method = ");
            System.out.println(a - b);
        }
      
        private static void div(int a, int b)
        {
            System.out.print("Answer by Private static method = ");
            System.out.println(a / b);
        }
    }
      
    class Temp implements TempI {
      
        @Override
        public void mul(int a, int b)
        {
            System.out.print("Answer by Abstract method = ");
            System.out.println(a * b);
        }
      
        public static void main(String[] args)
        {
            TempI in = new Temp();
            in.mul(2, 3);
            in.add(6, 2);
            TempI.mod(5, 3);
        }
    }

    
    

    OUTPUT : Answer by Abstract method = 6              // mul(2, 3) = 2*3 = 6
             Answer by Private method = 4               // sub(6, 2) = 6-2 = 4 
             Answer by Private static method = 3        // div(6, 2) = 6/2 = 3
             Answer by Default method = 8               // add(6, 2) = 6+2 = 8
             Answer by Private static method = 1        // div(5, 3) = 5/3 = 1 
             Answer by Static method = 2                // mod(5, 3) = 5%3 = 2
    

     
    Rules For using Private Methods in Interfaces

    • Private interface method cannot be abstract and no private and abstract modifiers together.
    • Private method can be used only inside interface and other static and non-static interface methods.
    • Private non-static methods cannot be used inside private static methods.
    • We should use private modifier to define these methods and no lesser accessibility than private modifier.

     
    So, from above it can be concluded that java 9 private interface methods can be static or instance. In both cases, the private method is not inherited by sub-interfaces or implementations. They are mainly there to improve code re-usability within interface only – thus improving encapsulation.



Similar Reads

private vs private-final injection of dependency
Dependency Injection (DI) is essential for improving code modularity, maintainability, and testability in the context of sophisticated Java programming. Choosing between private and private-final injection for dependencies is a typical DI concern. We will examine the distinctions between these two strategies in this post, as well as their applicati
5 min read
Access specifier of methods in interfaces
In Java, all methods in an interface are public even if we do not specify public with method names. Also, data fields are public static final even if we do not mention it with fields names. Therefore, data fields must be initialized. Consider the following example, x is by default public static final and foo() is public even if there are no specifi
1 min read
Two interfaces with same methods having same signature but different return types
Java does not support multiple inheritances but we can achieve the effect of multiple inheritances using interfaces. In interfaces, a class can implement more than one interface which can't be done through extends keyword. Please refer Multiple inheritance in java for more. Let's say we have two interfaces with same method name (geek) and different
2 min read
Private and final methods in Java
When we use final specifier with a method, the method cannot be overridden in any of the inheriting classes. Methods are made final due to design reasons. Since private methods are inaccessible, they are implicitly final in Java. So adding final specifier to a private method doesn't add any value. It may in-fact cause unnecessary confusion. class B
1 min read
Can we override private methods in Java?
Let us first consider the following Java program as a simple example of Overriding or Runtime Polymorphism. [GFGTABS] Java class Base { public void fun() { System.out.println("Base fun"); } } class Derived extends Base { public void fun() { // overrides the Base's fun() System.out.println("Derived fun"); } public static void
4 min read
Static methods vs Instance methods in Java
In this article, we are going to learn about Static Methods and Instance Methods in Java. Java Instance MethodsInstance methods are methods that require an object of its class to be created before it can be called. To invoke an instance method, we have to create an Object of the class in which the method is defined. public void geek(String name) {
5 min read
Callback using Interfaces in Java
Callback in C/C++ : The mechanism of calling a function from another function is called “callback”. Memory address of a function is represented as ‘function pointer’ in the languages like C and C++. So, the callback is achieved by passing the pointer of function1() to function2().Callback in Java : But the concept of a callback function does not ex
4 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
Generic Constructors and Interfaces in Java
Generics make a class, interface and, method, consider all (reference) types that are given dynamically as parameters. This ensures type safety. Generic class parameters are specified in angle brackets “<>” after the class name as of the instance variable. Generic constructors are the same as generic methods. For generic constructors after th
5 min read
Interfaces and Polymorphism in Java
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JA is that Java tries to connect every concept in the language to the real world with the help
6 min read
Which Java Types Can Implement Interfaces?
In Java there is no concept of multiple-inheritance, but with the help of interface we can achieve multiple-inheritance. An interface is a named collection of definition. (without implementation) An interface in Java is a special kind of class. Like classes, interface contains methods and members; unlike classes, in interface all members are final
7 min read
Match Lambdas to Interfaces in Java
One of the most popular and important topics is lambda expression in java but before going straight into our discussion, let us have insight into some important things. Starting off with the interfaces in java as interfaces are the reference types that are similar to classes but containing only abstract methods. This is the definition of interface
5 min read
Types of Interfaces in Java
In Java, an interface is a reference type similar to a class that can contain only constants, the method signatures, default methods, and static methods, and its Nested types. In interfaces, method bodies exist only for default methods and static methods. Writing an interface is similar to writing to a standard class. Still, a class describes the a
6 min read
How to Implement Multiple Inheritance by Using Interfaces in Java?
Multiple Inheritance is a feature of an object-oriented concept, where a class can inherit properties of more than one parent class. The problem occurs when methods with the same signature exist in both the superclasses and subclass. On calling the method, the compiler cannot determine which class method to be called and even on calling which class
2 min read
Interfaces and Inheritance in Java
A class can extend another class and can implement one and more than one Java interface. Also, this topic has a major influence on the concept of Java and Multiple Inheritance. Note: This Hierarchy will be followed in the same way, we cannot reverse the hierarchy while inheritance in Java. This means that we cannot implement a class from the interf
7 min read
Access modifiers for classes or interfaces in Java
In Java, methods and data members can be encapsulated by the following four access modifiers. The access modifiers are listed according to their restrictiveness order. 1) private (accessible within the class where defined) 2) default or package-private (when no access modifier is specified) 3) protected (accessible only to classes that subclass you
1 min read
Interfaces in Java
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a behavior. A Java interface contains static constants and abstract methods. What are Interfaces in Java?The interface in Java is a mechanism to achieve abstraction. Traditionally, an interface cou
11 min read
Functional Interfaces in Java
Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some of the primitive data types and primitive methods for integrity and simplicity. There are no solely functions present in a
10 min read
How to Create Interfaces in Android Studio?
Interfaces are a collection of constants, methods(abstract, static, and default), and nested types. All the methods of the interface need to be defined in the class. The interface is like a Class. The interface keyword is used to declare an interface. public interface AdapterCallBackListener { void onRowClick(String searchText); } public interface
4 min read
Why Enum Class Can Have a Private Constructor Only in Java?
Every enum constant is static. If we want to represent a group named constant, then we should go for Enum. Hence we can access it by using enum Name. Enum without a constructor: enum Day{ SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; } Enum with a constructor: enum Size { SMALL("The size is small."), MEDIUM("The size is medium."),
2 min read
Public vs Private Access Modifiers in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access mo
3 min read
Public vs Protected vs Package vs Private Access Modifier in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access mo
7 min read
Package vs Private Access Modifiers in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
3 min read
Private vs Final Access Modifier in Java
Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not etc. we can specify this information by using an appropriate keyword in java called access modi
3 min read
Protected vs Private Access Modifiers in Java
Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers. Access Modifier 1: Protected The methods or variables declared as protected are accessible wit
2 min read
Private vs Protected vs Final Access Modifier in Java
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access mo
5 min read
Private Constructors and Singleton Classes in Java
Let's first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it's made private, then it can only be accessed inside the class. Do we need such 'private constructors ' ? There are various scenarios where we can use private constructors.
2 min read
How to call private method from another class in Java with help of Reflection API?
We can call the private method of a class from another class in Java (which is defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private methods of different classes we will use Reflection API. To call the private method, we will u
3 min read
Java.util.BitSet class methods in Java with Examples | Set 2
Methods discussed in this post: BitSet class methods. / / | | \ \ set() xor() clone() clear() length() cardinality() We strongly recommend to refer below set 1 as a prerequisite of this. BitSet class in Java | Set 1 set() : java.util.BitSet.set() method is a sets the bit at the specified index to the specified value. Syntax:public void set(int bitp
4 min read
Java.io.BufferedWriter class methods in Java
Bufferreader class writes text to character-output stream, buffering characters.Thus, providing efficient writing of single array, character and strings. A buffer size needs to be specified, if not it takes Default value. An output is immediately set to the underlying character or byte stream by the Writer.Class Declaration public class BufferedWri
5 min read
Practice Tags :
three90RightbarBannerImg