The first king of the Java Empire was officially enthroned and officials came to congratulate him.

Minister A said, “Congratulations to your Majesty on your accession to the throne. In order to attract more programmers to join our country, I suggest improving OOP features of our Java language, encapsulation, inheritance and polymorphism as soon as possible.”

“One by one,” the king said, “let’s talk about encapsulation. Now that we can put data and methods into a class, we can find a way to hide information and limit access to them. I’ve heard that a lot of people are using C++.

Minister b was very fond of C++. “your majesty,” he said, “C++ has pubic, private, protected and other keywords that can be used to modify properties and methods. We can use them directly.”

public class Person{    private String name;    private int age;    public String getName(){        return name;    }    public int getAge(){        return age;    }}Copy the code

“So good! The king approved, but rolled his eyes and thought of Python a few years earlier. “How does Python deal with encapsulation?” he asked.

“Python is simple,” he said, “with two underscores to indicate private properties and methods.”

Class Person: def __init__(self, name): self. Name = name # self. Return self.__agep = Person(" Andy ")# Print (p.__age) # print(p.__secret())Copy the code

But the king said, “Well, it’s pretty simple. Just underline it. It’s very simple.

The second minister looked down on the scripting language and said, “No, your Majesty has no idea that Python, even if underlined, is only ‘pseudo-private’ properties and methods.”

“What is pseudo private?”

“So the outside world still has a way to access them!”

Print (p._person__age) # 10print(P._person__secret ()) # 10Copy the code

“What kind of private property and method is that? It’s not pure.” Minister b continues to repair the knife.

The king said, “Well, forget it. What about JavaScript? How does he achieve encapsulation?”

The Chinese ministers looked at each other. What the hell is this? Why haven’t you heard of it?

(Note: JavaScript was invented later than Java, and the King of Java has probably gone back in time.)

“Your Majesty, Python has a mechanism for grouping multiple classes together into a cohesive unit. Why don’t we do the same with Java?”

The king glared at his minister and scolded him, “Don’t learn Python for everything! We have to have something unique. To organize a class, we can use package. A package corresponds to a directory of the file system, under which there can be multiple class files. If a class is not decorated by public, it can only be accessed by classes belonging to the same package, not by classes belonging to other packages. Isn’t this a good design? !”

The king felt very proud.

There are three classes A, B, and C in the same package. Only class A can be accessed by external packages and can act as the “interface” of this package. C, B,C,C,C,C, B,C,C,C, B,C,C,C, B,C,C,C, B,C,C,C, B,C,C,C,C, B,C,C,C,C, B,C,C,C

As long as A does not change, it will not affect the use of the outside world, and B and C can change how they want!

The first minister carefully asked, “What if I just want to expose class B in foo.core to foo. CMD and block class B from other packages?”

“How can there be such a ‘sick’ need?” Both ministers expressed their disbelief.

“The demands of programmers are endless,” the king pondered. “There will always be exceptions. The need exists.

The second minister, who was familiar with C++, quickly added: “your majesty, C++ has a concept of friend class. For example, if you declare a friend Class LinkedList in a class Node, then the LinkedList can access the properties and methods of the Node class.”

Minister A strongly opposed this approach: “Not good, although it seems to provide programmers with convenience, but to the encapsulation of a big hole, if abused, the consequences are unimaginable.”

The king agreed, “Well, let’s give it up. Keep it simple. If he really wants to access class B, there are two ways to do it :(1) make class B public, and (2) delegate through the interface class A.”

In the blink of an eye, king Java has reached the ninth world.

On that day, Python and JavaScript emissaries from neighboring countries came to visit and were warmly received by the king. During the meeting, they talked about the problems of Java Package.

Although the Java package approach is good, it still has major drawbacks, the biggest of which is that many of the classes in the package are public, resulting in a situation like this.

The org.foo. API was supposed to provide an interface for the Client to call, but as soon as foo.jar is placed in the classpath, the classes in the other two packages, org.foo.impl and org.foo.core, are also exposed.

The JavaScript messenger said, “Oh, I thought a JAR file in your country was a reusable module, but now it’s not enough!”

“No wonder people say that your jar file is a zip of your class, and your classpath is a tiling of your classes.” The Python messenger laughed.

The Java King was a little angry, but his face didn’t show it. “How did your country do it?”

Python’s own Module seems to be doing the same thing, and private can only be implemented by convention (underlining variables and methods), since it is still accessible by convention.

JavaScript doesn’t even have a Module or package.

The Java king said: “Simple JAR files lack an important feature: hiding the internal implementation, we intend to make an important change and define the real module!”

“See? I’m going to use a file called module-info.java to define which packages in a module can be exported. Only those exported packages can be called by the Client. The other packages are invisible to the Client.”

Seeing this design, each minister felt good. With a module, you really define the interface that is accessible to the outside world. Except for the package of the interface, other packages are not accessible, completely realizing encapsulation.

The Python emissary stared at the diagram for a moment and said, “No, suppose there was code like this:”

FooService service = new FooServiceImpl();

FooService is a class under the org.foo. API package, FooServiceImpl is a class under org.foo.impl, according to your modularity requirements, this FooServiceImpl is not accessible to clients, How do I create FooService?”

The Java king thought that the Python emissary was familiar with my Java language, which made me embarrassed.

“Your Majesty, I think we can solve it with factory mode!” Finally a minister came to the rescue. “Create a new class FooServiceFactory, put it in a package called org.foo. API, and call it publicly.”

public class FooServiceFactory{    public static FooService getFooService(){        return new FooServiceImpl();    }}Copy the code

The Python emissary continues to press: “Unfortunately, FooServiceFactory is an API package, but it needs to know the implementation of the IMPL package. If you want to add an implementation of FooService, you have to modify it. Or improper ah!”

Suddenly, the Java King patted his head and said, oh, how did I forget ServiceLoader?

I can split the original module into two modules, org.foo. API for the interface and org.foo.provider for the implementation.

Provider specifically states that this module provides an implementation of FooService!

provides org.foo.api.FooService with  org.foo.provider.FooServiceImpl

The Python emissary is still confused: “What about the client?”

“Simple, Client code can be written like this:”

Iterable<FooService> iter = ServiceLoader.load(FooService.class); Iterate over iter, get FooService and use it.Copy the code

At run time, the Client code can use the ServiceLoader to find the specific implementation. Of course, there may be more than one implementation, but the Client can choose one.

Of course, the JDK must implement the ServiceLoader to get these concrete implementations.

“This solution, without breaking encapsulation, provides enough flexibility to assemble objects at run time, your Majesty!” Ministers fawned over each other.

Seeing this, the Python emissary stopped talking and began to drink.

The JavaScript messenger didn’t speak for a long time, wondering, am I a little behind The Times? Python has modules, Ruby has modules, and the modularity of Java is in full swing. Modularity greatly improves encapsulation, if you want to carry out the development of large projects this modularity is indispensable, think about their own messy JS files, it is time to make a change……

(after)

Code farmers turn over, with the story to explain the nature of technology, more exciting articles, please move to code farmers turn over three years article essence