"Java Programming Logic" Chapter 5 Class Extension

Chapter 5 Class Extension

Chapter 5 mainly introduces interfaces, abstract classes, internal classes and enumerations.

The nature of the interface

In many cases, what we care about is not the type of the object, but the ability of the object. We require an object to provide a certain ability, regardless of its type. The interface is used to describe the capabilities that an object can provide.

The interface declares a set of capabilities, but it does not implement this capability by itself, it is just a convention. The interface involves the interaction of two parties' objects. One party needs to implement this interface, and the other party uses this interface, but the two parties do not directly depend on each other. They only interact indirectly through the interface.

The definition of the interface uses interfacekeywords. As follows

public interface MyComparable {
    
    
    int compareTo(Object other);
}

Before Java 8, methods cannot be implemented in interfaces, and interface methods do not need to add modifiers, and the default is public abstract.

A class can implement an interface to indicate that the object of the class has the capabilities represented by the interface. Use implementskeywords to implement the interface .

public class Point implements MyComparable{
    
    
    ...
   @Override
    public int compareTo(Object other) {
    
    
        ...
    }
}

Need to override the method defined by the interface in the class to implement the interface. When using generics, you need to use it instanceofto check the type of the object to avoid unnecessary errors.

A class can implement multiple interfaces to indicate that the objects of the class have multiple capabilities.

public class Test implements interface1, interface2{
    
    
    
}

Interfaces cannot be newused to create interface objects. The only way to use an interface is to implement the interface through a class, then create an object of this class and call the object's interface method. The object that implements the interface can be assigned to the variable of the interface type, similar to the relationship between the parent class and the child class.

This is where the power of the interface lies. We can consider the capabilities of the object uniformly without the type of object, that is, the idea of ​​interface-oriented programming.

More importantly, the interface reduces coupling and improves flexibility. The code that uses the interface depends on the interface itself, not the specific type of the interface. The program can replace the implementation of the interface according to the situation without affecting the decoupled users.

Variables can be defined in the interface, but the variable type ispublic static final

public interface Interface1{
    
    
    public static final int a = 0;
}

Interfaces can be inherited. Unlike class inheritance, interface inheritance supports multiple inheritance.

public interface IBase1{
    
    
    void method1();
}

public interface IBase2{
    
    
    void method2();
}

public interface IChild extends IBase1, IBase2{
    
    
    
}

Class inheritance and implementation interface can coexist.

public class Child extends Base implements IChild{
    
    
    
}

Interfaces can also use instanceofkeywords to determine whether an object implements a certain interface.

Point p = new Point();
if( p instanceof MyComparable) {
    
    
    
}

You can use interfaces and composition to effectively replace inheritance.

Abstract class

An abstract class is an abstract class. Abstraction is relative to concrete. Generally speaking, concrete classes have direct corresponding objects, but abstract classes do not. It expresses abstract concepts, such as the graphic class Shape. Methods of abstract concepts are generally defined as abstract methods, for example, drawmethods of abstract classes are abstract methods. Because abstract classes don't know how to implement methods, only subclasses (concrete classes such as Circle) know how to implement them. Both abstract classes and abstract methods are abstractdeclared using keywords.

public abstract class Shape{
    
    
    public abstract void draw();
}

A class that defines an abstract method must be declared as an abstract class, but an abstract class can have no abstract method. Abstract classes cannot be used newto create objects, and subclasses must be used to create objects. After a class inherits an abstract class, it must implement all the abstract methods defined in the abstract class, unless it is also declared as an abstract class.

public class Circle extends Shape{
    
    
    @Override
    public void draw(){
    
    
        
    }
}

Although abstract classes cannot create objects, they can declare variables of abstract classes and refer to objects of concrete subclasses of abstract classes.

Shape shape = new Shape();
shape.draw();

The introduction of abstract classes to guide users to use them correctly and reduce uselessness. Using an abstract method instead of an empty method body, the subclass must implement the method, and it is impossible to ignore it. If it is ignored, a compilation error will occur.

Abstract classes and interfaces are fundamentally different. Instance variables cannot be defined in interfaces but abstract classes can. A class can implement multiple interfaces but can only inherit one class.

Abstract classes and interfaces are in cooperation rather than substitution. They are often used together, interface declaration capabilities, abstract classes provide default implementations and implement all or part of the methods. An interface often has a corresponding abstract class. For example Collection, the AbstractCollectionabstract class corresponding to the interface .

For a specific class that needs a certain ability, there are two choices. One is to implement the interface and implement all the methods yourself, and the other is to inherit the abstract class and rewrite the methods as needed. The advantage of inheritance is to reuse the code, only need to rewrite the required part, and the code to be written is relatively small and easy to implement. However, if this concrete already has a parent class, then you can only choose to implement the interface.

The essence of inner classes

Generally speaking, each class corresponds to an independent Java source file. But a class can also be placed inside another class, called an inner class , relatively speaking, the class that contains it is called an outer class .

The internal class is just the concept of the Java compiler. For the Java virtual machine, it does not know the internal class. Each internal class will eventually be compiled into an independent class to generate an independent bytecode file.

The inner class can easily access the private variables of the outer class.

In Java, there are four main types of internal classes according to the location and method of definition.

  • Static inner class
  • Member inner class
  • Method inner class
  • Anonymous inner class

Method inner classes are defined and used within a method, anonymous inner classes have a smaller scope, and neither of these two types can be used externally. Member inner classes and static inner classes can be used externally, but they can all be declared asprivate

Static inner classes are defined in the same way as static variables and static methods, all with statickeywords.

public class Outer{
    
    
    public static class StaticInner{
    
    
        public void innerMethod() {
    
    
            ...
        }
    }
}

The static inner class can directly access the static variables and methods of the outer class, but cannot access the instance variables.

publicThe static inner class can be used externally, but it needs 外部类.静态内部类to be used in a way.

Outer.StaticInner si = new Outer.StaticInner();
si.innerMethod();

The definitions of member inner classes and static inner classes are similar, but there are no staticmodifiers.

public class Outer{
    
    
    private int a = 100;
    
    public class Inner{
    
    
        public void innerMethod() {
    
    
            System.out.prinln("outer a = " + a);
            Outer.this.action();
        }
    }
    
    private void action() {
    
    
     	System.out.println("action");   
     }
    public void test() {
    
    
        Inner inner = new Inner();
        inner.innnerMethod();
    }
}

The member inner class can also directly access the instance variables and methods of the outer class, and can also use 外部类.this.xxxthe method to refer to the instance variables and methods of the outer class. But the latter is generally used when the methods and variables of the inner class of the member have the same name as the outer class

The essence of enumeration

Enumeration enumis a special data type. Its value is limited and can be enumerated, so it is called enumeration type.

An example of the definition of an enumeration class is as follows.

public enum Size {
    
    
    SMALL, MEDIUM, LARGE
}

Enumerations enumare defined using keywords , and each value of the enumeration type is separated by a comma ,. Enumeration types can be defined as a separate file, or they can be defined inside other classes.

The definition of enumerated type variables is as follows.

Size size = Size.MEDIUM;

The toString()sum name()method of the enumeration variable size.toString()returns the literal value of the enumeration variable, and the return is MEDIUM.

Enumeration variables can be used ==and equals()compared. Because the enumeration values ​​are in order, you can compare the sizes. The order of the enumeration values ​​is determined when the enumeration type is defined, starting from 0. Enumeration values ​​are ordinal()returned by methods .

Enumeration types all implement the Java API Comparableinterface, which can compareTobe compared with other enumeration values through methods , which is actually ordinalthe size of the comparison .

The enumeration type can be used in switchthe judgment condition, but casethe label in can not be prefixed with the enumeration type.

switch(size) {
    
    
    case SMALL:
        ...
       break;
        
    case MEDIUM:
       ...
       break;
        
    case LARGE:
       ...
       break;
}

Enumeration types have a static valueOf(String)method that can return the enumeration value corresponding to the string.

System.out.println(Size.valueOf("SMALL"));

Enumeration types also have a static valuesmethod that returns an array that includes all enumeration type variables, in the same order as in the declaration.

for(Size size : Size.values()) {
    
    
	System.out.println(size);
}

In fact, defining static integer variables in the class can also achieve the function of enumeration, but the enumeration type has the following advantages.

  • The syntax for defining enumerations is more concise.
  • Enumerated types are more secure. An enumeration type variable, their value is either null, or one of the enumeration values, it cannot be other values. If you use an integer variable, its value cannot be restricted.
  • Enumeration types have many easy-to-use built-in methods.

The enumeration type will actually be compiled by the Java compiler into a corresponding finalclass, which inherits the java.lang.Enum class in the Java API.

Generally, enumeration type variables will be converted into corresponding class variables. In the switch statement, the enumeration value will be converted into its corresponding ordinal value. Enumeration types are actually classes, but because the compiler automatically does a lot of work, the use of enumeration types is more concise, safe and convenient.

Enumeration types can also have instance variables and methods. The definition of the enumeration value needs to be placed at the beginning and ;end of the class definition .

public enum Size {
    
    
    SMALL("S", "小号"), 
    MEDIUM("M","中号"), 
    LARGE("L","大号");
    
    private String attribute;
    private String title;

    private Size(String attribute, String title) {
    
    
        this.attribute = attribute;
        this.title = title;
    }

    public String getAttribute() {
    
    
        return this.attribute;
    }

    public String getTitle() {
    
    
        return this.title;
    }
}

Guess you like

Origin blog.csdn.net/NelsonCheung/article/details/110358505