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?