Java methods private by default

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.

Читайте также:  What is atomicinteger in java

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.

Источник

Java Access Modifiers

Java provides four access modifiers to set access levels for classes, variables, methods and constructors i.e. public, private, protected and default. These access level modifiers determine whether other classes can use a particular field or invoke a particular method.

Let’s quickly compare these access modifiers in nutshell.

  • public – accessible everywhere
  • protected – accessible in the same package and subclasses outside the package
  • default – accessible only in the same package
  • private – accessible only in the same class

The access specifiers can be ordered based on their strictness as below. The public is the least restrictive, and the private is the most restrictive.

public > protected > package-private (or default) > private

The public members are accessible from everywhere. A public class, method, constructor, or interface could be accessed from any other class in the application. However, if the public class we are trying to access is in a different package, then we must import the class before using it.

public class Data < private String format; public String getFormat() < return this.format; >public void setFormat(String format) < this.format = format; >>

In the above example, getFormat() and setFormat() methods are public so they can be accessed from any class.

Please note that the fields in an interface are implicitly public static final and the methods in an interface are, by default, public .

The protected members are accessible by the classes of the same package and the subclasses outside the package.

In Data class, the method displayMessage() is declared protected, so it can be accessed by all the classes present in the same package where HelloWorld.java is present, as well as child classes present in other packages as well.

If we try to access the displayMessage() in another package without extending the Data class, we get the following compilation error:

'displayMessage()' has protected access in 'com.howtodoinjava.core.basic.accessModifiers.package1.Data'

Protected access modifier

When we inherit the Data class, then we can access the displayMessage() outside the current package.

public class Main extends Data < public static void main(String[] args) < Main main = new Main(); main.displayMessage(); >>

The default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc. The default members are accessible only by the classes in the same package.

Let us remove the protected access from the displayMessage() in the Data class. It changes the access to default.

Now when we try to access the displayMessage() in the child class outside the package, we will start getting the compilation error:

'displayMessage()' is not public in 'com.howtodoinjava.core.basic.accessModifiers.package1.Data'. Cannot be accessed from outside package

default access modifier

The private access modifier is the most restrictive access level. The topmost classes and interfaces cannot be private. The private members are accessible within the same class only. The private methods, variables, and constructors can only be accessed within the declared class itself.

We are modifying the previous example again by changing the default access to private access for the displayMessage() method.

Now the method is private so no other class can access it directly.

2. Levels of Access Control

There are two levels of access control.

  • Class level access – allows modifiers to be public, or package-private (default).
  • Method level access – allows modifiers to be public, private, protected, or package-private (default).

Local variables and formal parameters cannot take access specifiers. Since they are inherently inaccessible to the outside according to scoping rules, they are effectively private.

Both private and protected can be (and frequently are) applied to nested classes and interfaces, just never top-level classes and interfaces.

Access levels affect us in two ways.

  • First, when you use classes that come from another source, access levels determine which members of those classes your own classes can use.
  • Second, when you write a class, you must decide what access level every member variable and every method in your class should have.

If other programmers use your class, you want to ensure that errors from misuse cannot happen. Access levels can help you do this.

Источник

Оцените статью