Separation of "description of methods" from their implementation. I used to tell you that if you want to allow calling methods of your class from other classes, then you need to mark them with the public keyword. If you want, that any methods could be caused only from your class, they need to be marked with a keyword private. In other words, we divide class methods into two categories: "for all" and "only for their own."

With the help of interfaces, this division can be strengthened even more. We will make a special “class for all”, and a second “class for our own people”, which we will inherit from the first. Here is how it will be:

Example 1

class Student { private String name; public Student(String name) { this.name = name; } public String getName() { return this.name; } private void setName(String name) { this.name = name; } 

Main class

  public static void main(String[] args) { Student student = new Student("Alibaba"); System.out.println(student.getName()); } 

Example 2

 interface Student { public String getName(); } class StudentImpl implements Student { private String name; public StudentImpl(String name) { this.name = name; } public String getName() { return this.name; } private void setName(String name) { this.name = name; } } 

We have divided our class into two: the interface and the class inherited from the interface.

- And what is the advantage?

- The same interface can implement (inherit) different classes. And everyone can have their own behavior. As well as ArrayList and LinkedList are two different implementations of the List interface.

Thus, we hide not only various implementations, but even the class itself that contains it (only the interface can appear in the code everywhere). This allows very flexible, right in the process of execution of the program, to substitute one object for another, changing the object's behavior secretly from all the classes that use it.

This is a very powerful technology combined with polymorphism. It is now far from obvious why this should be done. You must first encounter programs consisting of tens or hundreds of classes in order to understand that interfaces can greatly simplify your life.

I do not really understand why we are making the setter private so that we can simply get the data thanks to the getter?

  • setter private is some very deep thought of the author of this code, which has nothing to do with the example being examined - Stranger in the Q
  • Because it is not "for everyone" - Roman C
  • This is most likely a print. Setters as rules are declared public. - Farkhod Daniyarov

1 answer 1

In my opinion, this example of the interface and its implementation is not very successful. From this the question arises: "Why, in fact, use the interface?". For myself, I understood this: The interface is needed when several implementations are envisaged . For clarity, consider the class StudentService , which will have getAll() and getByName() methods (I think the names of the methods speak for themselves).

 public class StudentService { public List<Student> getAll() { // ... } public Student getByName(String name) { // ... } } 

Obviously, there can be more than one implementation of this interface. Students can "take" from a database, from a file, after all, it may just be a static array in the class itself. Also, for clarity, let's introduce a class StudentController whose task is to display information about the student / students. It can be both an android application and a desktop, it is not important, it is important that the StudentController class will use the StudentService .

 public class StudentController { private StudentService studentService; public StudentController(StudentService ss) { this.studentService = ss; } public void showStudentInfo() { String name = ...; // получаем имя студента Student student = this.studentService.getByName(name); // находим студента по имени // отображаем информацию } } 

Now the field private StudentService studentService is a specific class (in which information is taken, for example, from a static array). Now, let's say I want to add a service to search for students in the database and use it in the StudentController . What do I need to do for that? First, obviously, create the class itself (say DatabaseStudentService ), which will interact with the database. Secondly, in StudentController you need to change the type from StudentService to DatabaseStudentService . And here you can notice the following problem: every time you want to change the StudentService you need to change the StudentController . To avoid this, you need to enter the StudentService interface (as long as it was a specific class) and the implementation:

 public interface StudentService { public List<Student> getAll(); public Student getByName(String name); } public class StaticArrayStudentService implements StudentService { // этот класс содержит конкретную реализацию } public class DatabaseStudentService implements StudentService { // этот класс содержит конкретную реализацию } 

To all this, I used a technique called Dependency Injection . That is, I create an instance of a class not in the StudentController class StudentController , but "outside of it" (passing StudentService as a constructor parameter):

 StudentService ss = new DatabaseStudentService(); StudentController sc = new StudentController(ss); 

Now, in order to change the StudentService implementation in the StudentController you need to change the first line in the code above (the StudentController class remains unchanged) .

Why does the Student class have a private setter? Probably so that the student’s name cannot be changed (indeed, in real life, the person’s name does not change, well, if the person is law-abiding;)).

Too much happened, I hope my answer will help you a little to understand!

  • Dependency injection is performed using one of the implementations of the IoC pattern and the corresponding framework. Interfaces are very well suited for establishing connections between bins, for which the methods heter and seters play a special role. If you need a deeper understanding of the concept of abstraction, then you can read ru.stackoverflow.com/a/818624/204920 - Roman C
  • @RomanC I don’t understand why we made the Setter private for this example so that no one could change our meaning? But why do it? - user331073 pm
  • @Mike I don’t know how to explain this to you, but the method is not contact, so the author made it private, he certainly would have to decide which methods to make virtual, but apparently if the method was private initially, then you can’t make a contract for him. - Roman C
  • @MikeMclaren I wrote at the end that the name of the student should not change in a good way, so the setter is private. There are so-called Immutable (immutable) classes, read about it, if you are so interested. - not a Programmer
  • @MikeMclaren which fields to make changeable (setter - public), and which ones unchangeable (setter - private) usually derives from common sense. - not a Programmer