Hello, ladies and gentlemen, last time we talked about the Java encapsulation example, this time let’s continue with that example. Stop gossiping and return to the truth. Let’s Talk Android!

See, in Java, in addition to classes have encapsulation function, interface also has this function, let’s use pseudo code to demonstrate interface encapsulation function.

interface A
{ 
    permission type value; 
    permission type function(); // don't do anything
}
Copy the code

Interface in pseudocode is a Java keyword that represents the type of interface. A is the name of the interface. The content in braces is the content encapsulated by the interface. Like the contents of the class, they are divided into two parts:

Some are member variables of the interface; The other part is the member function of the interface;Copy the code

Normally, we do not encapsulate variables in interfaces, although this is syntactic if necessary. The encapsulation of an interface is special in that the member variables it encapsulates have public access by default and are modified with final and static to indicate that they are constants of the interface. Since they are added by default, we do not append these modifiers to member variables when we define the interface. In addition, member functions have a default rule, which is to use abstract to decorate member functions so that they default to abstract functions. Like member variables, member functions have public access by default. However, we often omit the abstract modifier when defining interfaces. As for the default access right, although the syntax defaults to public, it will have the same effect if you do not add it, but I recommend that you add access right when defining the interface.

The interface contains abstract methods, so it is a bit like an abstract class and cannot be used to instantiate objects. If you want to use an interface, you must implement abstract functions in the interface. A common approach is to define a class that implements abstract functions in the interface, and then instantiate objects of a class so that methods in the interface can be used. Here we show the process in pseudocode:

interface B 
{
    publie void func();
 };

class C implements B 
{
      public void func()
      {
          //do something
      };
 };

C object = new C(); 
object.func();
Copy the code

In the above pseudocode, we define interface B, then define class C, and implement interface B. In class C, we implement the abstract method func() in interface B; Finally we create an object of class C so that we can use methods in the interface via ojbect.func().

That’s it for Java encapsulation. If you want to know more examples, listen next time.