Guillermo Fuentes
Guillermo Fuentes

Reputation: 11

Correct way to create private methods in an interface Java

I'm working with a database and I create a public interface called Dao with extends from AutoCloseabe, so I have a class which implements this interface but I want to create some private methods there but they still need Autocloseable. So my question is, I can't create private methods in the interface without defining them in the interface. Which happens if I create a private method in the class but not overriding from Dao? They won't have autocloseable, will they?. And if not which solution can I implement?

Upvotes: 0

Views: 6903

Answers (2)

Some random IT boy
Some random IT boy

Reputation: 8457

Private methods don't make a lot of sense in an interface since the main idea of an interface is to provide an interface for objects to interact with eachother. Since private methods are not visible to other objects they can't use them to communicate and send messages.

If you would like to have private methods I would suggest you use an abstract class instead.

As a sum up:

Q: So my question is, I can't create private methods in the interface without defining them in the interface.

Exactly that's the main point for interface; they define a public API without caring about the internal implementation.

Q: What happens if I create a private method in the class but not overriding from Dao?

If you declare a method in an abstract class and you don't override it two things may happen:

  1. The method was marked as abstract: you'll get a compile error saying that your implementation class doesn't satisfy the specification of the parent class.

1.1 If you declared a method in an interface and you don't implement it you will get the same error stating that your implementation class doesn't satisfy the interface it's trying to implement.

  1. The method was public and not marked as final in the abstract class: You may or may not override it. If you don't override it, the parent class implementation is going to be used; if you override it completely your child class code will be executed. If you call super.method() and then your implementation, both codes will be executed.

Upvotes: 1

Rogue
Rogue

Reputation: 11483

The motivation behind the introduction in Java 9 of private methods in interfaces is for the same reasons you would use private methods in any other class body. It allows you to break up the code into reusable, manageable methods which are not inherited:

default public boolean tryHeads() {
    return flip();
}

default public boolean tryTails() {
    return !flip();
}

private boolean flip() {
    return ThreadLocalRandom.current().nextBoolean();
}

This is grossly oversimplified. But see a similar question from me for more insight.

Upvotes: 2

Related Questions