Java 8 Improved Interface Abstract Class Enumeration Class

Posted by simonp on Tue, 21 Sep 2021 18:01:48 +0200

1.Basic syntax for defining interfaces:

[Modifier] interface Interface name extends Parent Interface 1, Parent Interface 2, ...
{
	Definitions of zero to multiple constants...
	Zero to more than one abstract method definition...
	Zero to many internal classes, interfaces, enumeration definitions...
	Zero to more than one default method or class method definition...
}	

Detailed description:

  • Modifiers can be public or omitted, and if the public access controller is omitted, the package permission access controller is used by default, meaning that the interface can only be accessed under the same package structure.
  • Interface names should follow the same naming rules as class names
  • An interface can have multiple direct parent interfaces, but an interface can only inherit interfaces, not classes

Because an interface definition is a specification, it cannot contain constructor and initialization block definitions. An interface can contain member variables (only static constants), methods (only Abstract instance methods, class methods, or default methods), and internal class (including internal interfaces, enumeration) definitions.

All members of an interface are public access rights. When defining interface members, access control modifiers can be omitted. If an access control modifier is specified, only public access control modifiers can be used.

For static constants defined in an interface, they are interface related, so the system automatically adds static and final modifiers to these member variables. That is, public static final, when defining member variables in an interface, whether or not public static is usedFinal modifier, member variables in an interface are always decorated with these three modifiers. There are no constructors or initialization blocks in the interface, so member variables defined in the interface can only specify default values when they are defined.

Methods defined in an interface can only be abstract methods, class methods, or default methods, so if the default method is not defined, the abstract modifier is automatically added to the normal method. When defining the normal method in an interface, public abstract is always used for the normal method in the interface, regardless of whether the public abstract modifier is used or not.To decorate. There can be no method implementation (body of method) for a common method in an interface.However, class methods (static modifications) and default methods must all have method implementations (method bodies)

Internal classes defined in interfaces, internal interfaces, and internal enumeration classes all use public statics as modifiers by default. Whether these modifiers are specified or not, they are automatically modified by public statics.

2.Java Initialization Block

Java uses a constructor to initialize a single object, which first initializes the state of the entire Java object and then returns the Java object to the program, thus making the information of the Java object more complete. Similar to a constructor, an initialization block can also initialize Java objects.

Initialization blocks are the fourth member that can appear in a Java class. There can be multiple initialization blocks in a class. There is an order between the same type of initialization blocks: the previously defined initialization blocks execute first, and the later defined initialization blocks execute later.

  • Syntax format of initialization block:
[Modifier] {
	// Executable code for initialization block
	...
}

The modifier of an initialization block can only be static, and the initialization block modified with static is called a static initialization block. The code inside the initialization block can contain any executable statement, including defining local variables, calling methods on other objects, and using branch, loop statements.

When creating a Java object, the system always calls the initialization block defined in the class before executing the construction method. If two common initialization blocks are defined in a class, the initialization block defined earlier is executed first, and the initialization block defined later is executed.

Initialization blocks are also a member of Java classes, but they have no name or identity, so they cannot be invoked through classes or objects. Initialization blocks are only implicitly executed when creating Java objects and are executed before the constructor is executed.

  • Sample program:
public class Main {
    // Execute initialization block to assign a instance variable to 6
    {
        a = 6;
    }
    // Then execute assigning a instance variable to 9
    int a = 9;
    public static void main(String[] args) {
        //The following code will output 9
        System.out.println(new Main().a);
    }
}
  • Run result:


  • Explanation:
    When Java creates an object, memory is allocated to all the instance variables of the object (provided the class is loaded), and then the program begins to initialize the instance variables in the order specified when the initialization block is executed first or the instance variables are declared.(The execution of the initial values specified in these two places allows them to be in the same order as they are arranged in the source code), then the initial values specified in the constructor are executed.

In fact, an initialization block is an illusion that once a Java class is compiled using the javac command, the initialization block in the Java class disappears - the code in the initialization block is "restored" to each constructor and precedes all the code in the constructor.

  • Static Initialization Block
    If an initialization block is defined with a static modifier, it becomes a static initialization block, also known as a class initialization block (a common initialization block is responsible for initializing objects, and a class initialization block is responsible for initializing classes).Static initialization blocks are class-related and will be executed during the class initialization phase rather than when an object is created. Therefore, static initialization blocks are always executed before ordinary initialization blocks.

Static initialization blocks are class-related and are used to initialize the entire class, usually to initialize class variables. Static initialization blocks cannot initialize instance variables.

3. Abstract methods and classes

Abstract methods and classes must be defined with abstract modifiers. Classes with abstract methods can only be defined as abstract classes, and abstract classes can have no abstract methods.
The rules for abstract classes and methods are as follows:

  • Abstract classes must be decorated with abstract modifiers, and abstract methods must be decorated with abstract modifiers. Abstract methods cannot have body.
  • An abstract class cannot be instantiated, nor can it use the new keyword to call the constructor of an abstract class to create an instance of it. Even if an abstract class does not contain an abstract method, it cannot create an instance.
  • Abstract classes can contain member variables, methods (both common and abstract), constructors, initialization blocks, and five components of internal classes (interfaces, enumerations). Constructors of abstract classes cannot be used to create instances, mainly for invocation by their subclasses.
  • Classes containing abstract methods (including those that directly define an abstract method or inherit an abstract parent class but do not fully implement the abstract methods contained by the parent class, or that implement an interface but do not fully implement the abstract methods contained by the interface) can only be defined as abstract classes.

4.Enum Class

An enumeration class is a special class that can also have its own member variables, methods that implement one or more interfaces, and can define its own constructors. A Java source file defines at most one enumeration class with public access, and the Java source file must have the same class name as the enumeration class.

  • Differentiation from common classes:
  1. Enumeration classes implement one or more interfaces, and enumeration classes defined with emnu inherit the java.lang.Enum class by default instead of the Object class by default, so enumeration classes cannot display inheritance from other parent classes. The java.lang.Enum class implements both java.lang.Serializable and java.lang.Comparable interfaces.
  2. Using emnu definitions, non-abstract enumeration classes default to final modifiers, so enumeration classes cannot derive subclasses
  3. The constructor of an enumeration class can only use the private access controller. If the constructor's access controller is omitted, the private modifier is used by default. If the access controller is forced, only the private modifier can be specified.
  4. All instances of an enumerated class must be explicitly listed on the first line of the enumerated class, or the enumerated class will never produce an instance. When these instances are listed, the public static final modifier is added automatically without the programmer showing it.
  5. Enumeration classes provide a value () method by default, which makes it easy to iterate through all the enumerated values.

4.1 Enumerate member variables, methods, and constructors of classes

public class Main {
    enum Gender{
        MALE,FEMALE;
        //Define a public-modified instance variable
        public String name;
    }
    public static void main(String[] args) {
        //Gets the enumeration value of the specified enumeration class through the valueOf() method of the Enum class
        Gender g = Enum.valueOf(Gender.class, "FEMALE");
        //Assign values directly to the name instance of an enumeration value
        g.name = "nv";
        //Direct access to the name instance variable of an enumerated value
        System.out.println(g.name);
    }
}

Run result:

public class Main {
    enum Gender{
        //The enumerated value here must call the corresponding constructor to create
        MALE("male"),FEMALE("female");
        private final String name;
        private Gender(String  name){
            this.name = name;
        }
        public String getName() {
            return name;
        }
    }
    public static void main(String[] args) {
        //Gets the enumeration value of the specified enumeration class through the valueOf() method of the Enum class
        Gender g = Enum.valueOf(Gender.class, "FEMALE");
        //Direct access to the name instance variable of an enumerated value
        System.out.println(g.getName());
    }
}

Run result:

4.2 Enumeration classes implementing interfaces

public class Main {
    private interface GenderDesc{
        void info();
    }
    enum Gender implements GenderDesc{
        //The enumerated value here must call the corresponding constructor to create
        MALE("male"){
            @Override
            public void info() {
                super.info();
                System.out.println("This enumeration value represents men");
            }
        }
        ,FEMALE("female"){
            @Override
            public void info() {
                super.info();
                System.out.println("This enumeration value represents women");
            }
        };
        private final String name;
        private Gender(String  name){
            this.name = name;
        }
        public String getName() {
            return name;
        }
        //Implementing methods in interfaces
        @Override
        public void info() {
            System.out.println("This is an enumeration class for defining gender");
        }


    }
    public static void main(String[] args) {
        //Gets the enumeration value of the specified enumeration class through the valueOf() method of the Enum class
        Gender g = Enum.valueOf(Gender.class, "FEMALE");
        //Direct access to the name instance variable of an enumerated value
        System.out.println(g.getName());
        g.info();
    }
}

Run result:

4.3 Enumeration classes containing abstract methods

public enum Main {
    PLUS{
        @Override
        public double eval(double x, double y) {
            return x+y;
        }
    },
    MINUS{
        @Override
        public double eval(double x, double y) {
            return x-y;
        }
    };
    //Define an abstract method for this enumeration class that provides different implementations for different enumeration values
    public abstract double eval(double x, double y);
    public static void main(String[] args) {
        System.out.println(Main.PLUS.eval(3,4));
        System.out.println(Main.MINUS.eval(3,4));
    }
}

Run result:

5.Reference Books

Crazy Java Handouts 3rd Edition (by Li Gang)

Topics: Java C# RESTful