Private method in interface java

Why doesn’t Java allow private members in interface?

@pst I wrote a workaround at the end of my answer — stackoverflow.com/a/10169894/348975. Does it address your concerns?

To future readers: as it’s currently written, the OP asks for private members, this is not limited to fields, but also includes methods.

14 Answers 14

«The Java programming language provides mechanisms for access control, to prevent the users of a package or class from depending on unnecessary details of the implementation of that package or class.»

Access control is all about hiding implementation details. An interface has no implementation to hide.

Since we can put nest classes inside an interface, we can put implementation on the interface. Doing so is very wrong, but we can.

Java 9 allows private methods in interface, It is logical after the addition of default methods, Ref: bugs.openjdk.java.net/browse/JDK-8071453

It’s not that bad as it sounds. The private methods in an interface can only be accessible by default methods in that same interface. One of the benefits is to help breaking implementation of default methods into meaningful smaller functions without breaking encapsulation.

In Java 9, private methods in interfaces are possible.

The javac compiler team is pleased announce the availability of compiler support for private methods in interfaces beginning with 9 b54 build of JDK.

Private interface methods are part of Java 9 as part of JEP-213. Since interfaces in Java 8 can have default methods, private methods allow for multiple default methods to use a shared private method.

As of Java 8, interfaces can have default methods, and as of Java 9, an interface is allowed to have a private methods which can only be accessed by default methods in the same interface.

An interface is used for describing an API which is provided by any class implementing the interface. Since an interface from its definition has no state there is no use of declaring field members in it.

There would be no way to implement such an interface. An answer to a question I posed strongly suggests that it would be impossible (without radically changing the rules) to implement an interface with private methods — this leaves open the question of why protected and package private methods are not allowed.

class OuterClass < void run ( MyInterface x ) < x . publicMethod ( ) ; // why not? x . protectedMethod ( ) ; // why not? x . packagePrivateMethod ( ) ; // why not? x . privateMethod ( ) ; // why not? >interface MyInterface < public abstract void publicMethod ( ) ; // OK protected abstract void protectedMethod ( ) ; // why not? abstract void packagePrivateMethod ( ) ; // in interface default is public, but why not package private private void privateMethod ( ) ; // impossible to implement >class MyImpl implements MyInterface < public void publicMethod ( ) < >// ok protected void protectedMethod ( ) < >// no sweat void packagePrivateMethod ( ) < >// no sweat private void privateMethod ( ) < >// not happening > > 

The below code should achieve the desired result. Even though all methods are public, only public method is effectively public. protected method is effectively protected. packagePrivateMethod is effectively packagePrivate. privateMethod is effectively private.

class WorkAround < void run ( MyPrivateInterface x ) < x . publicMethod ( ) ; x . protectedMethod ( ) ; x . packagePrivateMethod ( ) ; x . privateMethod ( ) ; >public interface MyPublicInterface < void publicMethod ( ) ; >protected interface MyProtectedInterface extends MyPublicInterface < void protectedMethod ( ) ; >interface MyPackagePrivateInterface extends MyProtectedInterface < void packagePrivateMethod ( ) ; >private interface MyPrivateInterface extends MyPackagePrivateInterface < void privateMethod ( ) ; >> 

According to the Java programming language scope of the private members is limited to the class in which it is declared and can be accessed only by methods of that class . But inteface doesn’t have a method body hence there is no use of declaring private members inside an interface .

Java allows private methods in an interface in Java 9. The default methods were introduced in Java 8. It is possible that multiple default methods want to share some code, then this code can be moved to a private method without exposing it to outer world. This bug has been fixed and starting in JDK 9 build 54, compiler support for private interface methods have been resurrected.

public interface IData < default void processData(int data) < validate(data); // do some work with it >default void consumeData(int data) < validate(data); // do some work with it >private void validate(int data) < // validate data >> 

It is because they would be useless.

There would be no way to call a private method.

Private members are an implementation detail. An interface is about the public role that a class can take on.

I disagree wrt «There would be no way to call a private method.» With the inner classes, there would be a way — stackoverflow.com/a/10169894/348975

Consider default methods of java 8. Interface I has default methods A and B with a lot of common code. To refactor this you would want method C that would contain just the shared code and being called by A and B. In Java 8 this would be a default method that is exposed to all interface implementors. in Java 9 C could be a private method visible only to default methods within I.

private fields would not be completely useless as other fields and inner classes could access them.

However private methods could not be implemented, even in nested classes, making them almost useless. You could read them using reflection, but that is rather an edge case.

Sorry for grave-digging here 🙁 How does docs.oracle.com/javase/7/docs/api/java/io/Serializable.html work in this case? Can’t people implement it and then overwrite the readObject and writeObject methods? I’m sure I’m missing something

Private members don’t make sense in interface. Interface is a way to access a class with defined methods where you don’t need to see the inners of that class.

Private members disagree to that.

Members of a class that are declared private are not inherited by subclasses of that class. Only members of a class that are declared protected or public are inherited by subclasses declared in a package other than the one in which the class is declared.

So you don’t have any working methods in an interface which can work with that private non-inheritable field, Then why should it exist?

Yep, can’t do that. For all those commenting on why it shouldn’t:

Imagine I have Class A, which utilizes interface I. Class B, extends Class A, therefore also inheriting all interface methods in A.

Now, imagine I want a private method in Class A, but want it contractually defined for other classes as well (Maybe a class C, which doesn’t necessarily extend Class B or A).

Perhaps for an «initialization» method, that I want for all classes using an I interface. But obviously I don’t want an initialization method to be public. since it should only be used once, or as the class deems necessary, not just because you want to use it all willy-nilly.

The only solution is a workaround, or by simply forcing the init method into the classes themselves without an interface.

I understand the reason not too, for sure, but still, it can come in handy sometimes. Clearly Oracle agrees as they’re allowing private interface methods in JDK 9.

What I did, for mine anyway, was place a simple boolean variable, that way the interface method (which should be private) can be flagged as true (initialized = true) after being set once. Then when called again the method simply does nothing. This way the interface method can be implemented as public, but since the constructor (of my class) calls the method first, this sets the variable to true, and so it can’t be called again.

Otherwise you’d have to try a different workaround if you only want the inner workings of the class to use it. perhaps a method itself sets a flag on and off as it uses it. When the flag is false, the method does nothing (this would be when someone calls it from outside the class). However, when the classes own methods call it, they quickly set the flag to true, then call the method, then set the flag to false??

In the end kind of mute. Probably just better for now to simply place the private class into the class itself and cut-out the interface altogether.

Источник

Private Methods in Interface – Java 9

Java 9 onward, you are allowed to include private methods in interfaces. Using private methods, now encapsulation is possible in interfaces as well.

In this java 9 tutorial, we will learn about interface private methods in detail.

Table of Contents Interfaces till Java 7 Static and defaults methods since Java 8 Private methods since java 9 Java 9 Private Interface Method Example Summary

In Java 7 and all earlier versions, interfaces were very simple. They could only contain public abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface.

public interface CustomInterface < public abstract void method(); >public class CustomClass implements CustomInterface < @Override public void method() < System.out.println("Hello World"); >public static void main(String[] args) < CustomInterface instance = new CustomClass(); instance.method(); >> Output: Hello World

Static and defaults methods since Java 8

From Java 8, apart from public abstract methods, you can have public static methods and public default methods.

public interface CustomInterface < public abstract void method1(); public default void method2() < System.out.println("default method"); >public static void method3() < System.out.println("static method"); >> public class CustomClass implements CustomInterface < @Override public void method1() < System.out.println("abstract method"); >public static void main(String[] args) < CustomInterface instance = new CustomClass(); instance.method1(); instance.method2(); CustomInterface.method3(); >> Output: abstract method default method static method

Access modifier ‘public’ is optional in all above interface method declarations. I have added them to improve readability only.

Private methods since java 9

Since java 9, you will be able to add private methods and private static method in interfaces.

These private methods will improve code re-usability inside interfaces. Foe example, if two default methods needed to share code, a private interface method would allow them to do so, but without exposing that private method to it’s implementing classes.

Using private methods in interfaces have four rules :

  1. Private interface method cannot be abstract.
  2. Private method can be used only inside interface.
  3. Private static method can be used inside other static and non-static interface methods.
  4. Private non-static methods cannot be used inside private static methods.
public interface CustomInterface < public abstract void method1(); public default void method2() < method4(); //private method inside default method method5(); //static method inside other non-static method System.out.println("default method"); >public static void method3() < method5(); //static method inside other static method System.out.println("static method"); >private void method4() < System.out.println("private method"); >private static void method5() < System.out.println("private static method"); >> public class CustomClass implements CustomInterface < @Override public void method1() < System.out.println("abstract method"); >public static void main(String[] args) < CustomInterface instance = new CustomClass(); instance.method1(); instance.method2(); CustomInterface.method3(); >> Output: abstract method private method private static method default method private static method static method

Java 9 Private Interface Method Example

Let’s see a demo to understand the private interface method’s usage.

I am creating a calculator class with two functions. First function will accept some integers and add all even numbers in it. Second function will accept some integers and add all odd numbers in it.

CustomCalculator.java – Interface

import java.util.function.IntPredicate; import java.util.stream.IntStream; public interface CustomCalculator < default int addEvenNumbers(int. nums) < return add(n ->n % 2 == 0, nums); > default int addOddNumbers(int. nums) < return add(n ->n % 2 != 0, nums); > private int add(IntPredicate predicate, int. nums) < return IntStream.of(nums) .filter(predicate) .sum(); >>

Main.java – Class

public class Main implements CustomCalculator < public static void main(String[] args) < CustomCalculator demo = new Main(); int sumOfEvens = demo.addEvenNumbers(1,2,3,4,5,6,7,8,9); System.out.println(sumOfEvens); int sumOfOdds = demo.addOddNumbers(1,2,3,4,5,6,7,8,9); System.out.println(sumOfOdds); >> Output: 20 25

In short, 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.

Let’s revisit all the allowed method types in java 9.

Method Type Since When
public abstract Java 7
public default Java 8
public static Java 8
private Java 9
private static Java 9

Drop me your questions in comments sections.

Источник

Private interface methods, example use-case?

«Support for private methods in interfaces was briefly in consideration for inclusion in Java SE 8 as part of the effort to add support for Lambda Expressions, but was withdrawn to enable better focus on higher priority tasks for Java SE 8. It is now proposed that support for private interface methods be undertaken thereby enabling non abstract methods of an interface to share code between them.» So says the specification for http://openjdk.java.net/jeps/213 and says in bug report https://bugs.openjdk.java.net/browse/JDK-8071453 . But I can’t really think of any use-case where this is necessary, even with the short explanation given above. May I ask for an example where «private interface methods» are useful in terms of code? EDIT: So the answer is that due to how default implementations have been added to interfaces in Java 8, there can be instances where the default implementations are using the same codebase. For example,

public interface MyInterface < default void initializeMyClass(MyClass myClass, Params params) < //do magical things in 100 lines of code to initialize myClass for example >default MyClass createMyClass(Params params) < MyClass myClass = new MyClass(); initializeMyClass(myClass, params); return myClass; >default MyClass createMyClass() < MyClass myClass = new MyClass(); initializeMyClass(myClass, null); return myClass; >> 

Silly example, I know. But let’s say that we want to use initializeMyClass(MyClass, Params) in both methods. However, if we do it like this (default method), then initializeMyClass(MyClass, Params) will be part of the public interface! To prevent that from happening, we can only keep the code of entire initializeMyClass(MyClass, Params) inside the createMyClass() default methods. Which results in code duplication, which is undesirable. Therefore, this causes problem with refactoring, and to remove such code duplication, private default methods are allowed. Thanks for answering!

Источник

Читайте также:  margin
Оцените статью