abstract class
When we declare a geometric figure class: circle, rectangle, triangle, etc., we find that these classes have common characteristics: calculating area, perimeter and obtaining figure details. Then these common features should be extracted into a common parent class. However, these methods cannot be implemented in the parent class, but should be implemented by the child classes. When the parent class declares these methods, it has only method signature and no method body. We call the method without method body as abstract method. Java syntax stipulates that classes containing abstract methods must be abstract classes.
- Abstract method: a method modified by abstract
- Abstract class: a class modified by abstract
Syntax format of abstract class
Syntax format of abstract method
Code example
package demo01; //Define abstract classes public abstract class Animal { //Methods in abstract classes can be 0 to n public abstract void eat();//Abstract method has no method body } //Subclasses to implement abstract classes class Cat extends Animal{ @Override public void eat() { System.out.println("I'm a cat. I eat fish"); } } //Test class class Test{ public static void main(String[] args) { //Create subclass object Animal cat = new Cat(); cat.eat(); //I'm a cat. I eat fish } }
The method rewriting at this time is the completion and implementation of the abstract method of the parent class by the subclass. The operation of rewriting this method is also called the implementation method.
matters needing attention
As for the use of abstract classes, the following are the details that should be paid attention to in syntax. Although there are many items, if you understand the essence of abstraction, you don't need to memorize by rote.
Abstract classes cannot create objects. If they are created, the compilation fails and an error is reported. Only objects whose non Abstract subclasses can be created.
- Understanding: suppose an object of an abstract class is created and an abstract method is called, but the abstract method has no specific method body and has no meaning.
Abstract classes also have construction methods, which are used to initialize parent class member variables when subclasses create objects.
- Understanding: there are default super() or manual super (argument list) in the construction methods of subclasses. You need to access the construction methods of parent classes.
Abstract classes do not necessarily contain abstract methods, but classes with abstract methods must be abstract classes.
- Understanding: an abstract class that does not contain an abstract method is designed to prevent the caller from creating this class object. It is usually used for some special class structure design.
Subclasses of abstract classes must override all abstract methods in the abstract parent class, otherwise, the compilation fails and an error is reported. Unless the subclass is also an abstract class.
- Understanding: assuming that all abstract methods are not overridden, the class may contain abstract methods. After creating objects, it is meaningless to call abstract methods.
Interface
An interface is a specification, which defines a set of rules, reflecting the real world "if you are / want to..., you must be able to..." My thoughts. Inheritance is a yes / no is-a relationship, while interface implementation is a yes / no has-a relationship.
- For example, whether you can connect with USB or whether you have USB communication function depends on whether you follow the USB interface specification
- For example, whether a java program can connect and use a database product depends on whether the database product implements the JDBC specification of Java design
The definition of interface, which is similar to the way of defining classes, but uses the interface keyword. It will also be compiled into Class file, but it must be clear that it is not a class, but another reference data type.
Declaration format of interface
package demo02; public interface DemoInterface { //constant public static int MAX = 33; //Abstract method void read(); void write(); //Default method public default void start(){ System.out.println("start"); } //Static method public static void show(){ System.out.println("Read and write at synchronous full speed"); } private void test(){ System.out.println("Private method"); } }
Member description of the interface
The interface defines the common behavior specifications of multiple classes. These behavior specifications are the channels for external communication, which means that a set of public methods are usually defined in the interface. It can be understood that an interface is a specification abstracted from multiple similar classes and does not need to provide a specific implementation
Before JDK8, only the following are allowed in the interface:
- Public static constants: public static final can be omitted
- Public abstract method: public abstract can be omitted
In jdk1 8, default methods and static methods are allowed to be declared in the interface:
- Public default method: public can be omitted and it is recommended to keep it, but default cannot be omitted
- Public static method: public can be omitted and it is recommended to keep it, but static cannot be omitted
In jdk1 At 9:00, the interface is added:
- Private method
In addition, there can be no other members, constructors or initialization blocks in the interface, because there are no member variables to initialize in the interface.
Use of interfaces
Interface, which cannot create objects, but can be implemented (similar to being inherited). The relationship between class and interface is implementation relationship, that is, class implements interface. This class can be called implementation class of interface or subclass of interface. The actions implemented are similar to inheritance and the format is similar, but the keywords are different. The implementation uses the implements keyword.
Implementation interface syntax format
be careful:
- If the implementation class of the interface is a non abstract class, you must override all abstract methods in the interface.
- The default method can be retained or overridden. When rewriting, do not write the word default. It is only used to represent the default method in the interface, and there is no concept of default method in the class
- Static methods cannot be overridden
package demo02; public class DemoClass implements DemoInterface { @Override public void read() { System.out.println("I can read"); } @Override public void write() { System.out.println("I can write"); } }
How to call the corresponding method
- For static methods of interfaces, directly use "interface name." Just call. It can only be called with "interface name." it cannot be called through the object implementing the class
- Abstract methods and default methods of interfaces can only be called by implementing class objects. Interface cannot directly create objects, only objects that implement classes can be created
package demo02; public class Test { public static void main(String[] args) { //Create and implement class objects, polymorphic DemoInterface b = new DemoClass(); //By implementing the abstract method of class object call override and the default method of interface, // If the implementation class is overridden, the overridden default method will be executed. If it is not overridden, the default method in the interface will be executed b.start(); b.read(); //Call the static method of the interface through the interface name DemoInterface.show(); } }
Multiple implementation of interface
I learned before that in the inheritance system, a class can only inherit one parent class. For interfaces, a class can implement multiple interfaces, which is called multiple implementation of interfaces. Moreover, a class can inherit a parent class and implement multiple interfaces at the same time.
Other precautions:
- When a class inherits a parent class and implements several interfaces, the member method in the parent class has the same name as the abstract method in the interface, and the subclass selects the member method of the parent class nearby
- When a class implements multiple interfaces at the same time, and multiple interfaces contain default methods with the same method signature. Either choose to keep one of them and choose which interface's default method to keep through the method of "interface name. super. Method name", or choose to completely override it.
- An interface can inherit from another or more interfaces. The interface inheritance also uses the extends keyword. The child interface inherits the methods of the parent interface.
- The implementation class implements the interface, which is similar to the subclass inheriting the parent class. Therefore, polymorphic references can also be formed between the variables of the interface type and the objects of the implementation class. The method is called through the variable of interface type, and the final execution is the method body implemented by your new implementation class object.
Comparable (internal comparator)
We know that if the size of data of basic data type (except boolean type) needs to be compared, the comparison operator can be used between them, but the comparison operator cannot be directly used to compare the size of referenced data type. So, how to solve this problem? Java specifies a standard interface for the size comparison of all reference data types, which is Java Lang. comparable interface:
public interface Comparable{ int compareTo(Object obj); }
So what do we do if we want to make our objects of a class comparable in size? Steps:
Step 1: the object of which class needs to be compared in size, and which class implements Java Lang. comparable interface and override the method
- The method body is how you compare the size of the current object with that of another specified object
Step 2: when the object is relatively large, call the compareTo method through the object, and decide who is big and who is small according to the return value of the method.
- this object (the object that calls the compareTo method) is larger than the specified object (the parameter object passed in compareTo()) and returns a positive integer
- this object (the object that calls the compareTo method) is smaller than the specified object (the parameter object passed in compareTo()) and returns a negative integer
- this object (the object that calls the compareTo method) is equal to the specified object (the parameter object passed in compareTo()) and returns zero
Code example:
//It is required to compare the size according to the salary. If the salary is the same, compare the size according to the number. @Override public int compareTo(Object o) { Employee emp = (Employee) o; if(this.getSalary() != emp.getSalary()){ return Double.compare(this.getSalary(), emp.getSalary()); } return this.id - emp.id; } //Other codes
Customize an array tool class MyArrays, which contains a static method that can use bubble sorting to sort any object array from small to large
public class MyArrays { public static void sort(Object[] arr) { //Bubble sorting for (int i = 1; i < arr.length; i++) { for (int j = 0; j < arr.length - i; j++) { //The purpose of forcing arr[j] to the Comparable interface type is to call the compareTo method //Of course, if the elements of the array do not implement this interface, ClassCastException will occur Comparable c = (Comparable) arr[j]; if (c.compareTo(arr[j + 1]) > 0) { Object temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } }
Comparator (external comparator)
If a class does not implement the Comparable interface, and it is inconvenient for you to modify this class (for example, for some third-party classes, you only have. Class files and no source files), what should you do if the objects of this class also have to be compared in size? If a class implements the Comparable interface and specifies the rules for comparing the size of two objects, but at this moment I don't want to compare the size according to its predefined method, but I can't modify it at will, because it will affect the use in other places, what should I do? At the beginning of designing the class library, JDK also considered this situation, so it added a Java util. Comparator interface
public interface Comparator{ int compare(Object o1,Object o2); }
So how do we compare the sizes of two objects of a class? Steps:
Step 1: write a class, which we call comparator type, to implement Java util. Comparator interface and rewrite the method
-
The method body is how you specify the size of the two objects
Step 2: when comparing the size, call the compare() method through the object of the comparator type, pass in the two objects to be compared as the arguments of the compare method, and decide who is big and who is small according to the return value of the method.
- o1 object greater than o2 returns a positive integer
- o1 object less than o2 returns a negative integer
- The o1 object is equal to o2 and returns zero
Code example: for a student class that does not implement the Comparable interface, define a custom comparator class first
class StudentScoreCompare implements Comparator{ @Override public int compare(Object o1, Object o2) { Student s1 = (Student) o1; Student s2 = (Student) o2; return s1.getScore() - s2.getScore(); } }
Test class
import java.util.Comparator; public class TestComparator { public static void main(String[] args) { Student stu1 = new Student("Zhang San",89); Student stu2 = new Student("Li Si",78); StudentScoreCompare ssc = new StudentScoreCompare(); if(ssc.compare(stu1, stu2)>0){ System.out.println(stu1 + ">" + stu2); }else if(ssc.compare(stu1, stu2)<0){ System.out.println(stu1 + "<" + stu2); }else{ System.out.println(stu1 + "=" + stu2); } } }
enumeration
Some types of objects are limited. There are many examples:
- Monday Sunday
- Gender: man (male), woman (female)
- Month: January December
- Season: Spring Winter
- Payment methods: Cash (cash), WeChatPay (WeChat), Alipay (Alipay), BankCard (bank card), CreditCard (credit card).
- Employee working status: Busy, Free, Vocation
- Order status: unpaid, Paid, Fulfilled, Delivered, Checked, Return, Exchange, Cancel
Enumeration type is essentially a kind, but the objects of this class are fixed and cannot be created by users at will.
- In jdk1 Before 5, programmers need to define enumeration types in a special way.
- In jdk1 After enum, the Java enum type can be defined quickly.
JDK1. Before 5
In jdk1 How to declare enumeration classes before 5?
- Constructor plus private privatization
- This class creates a set of constant objects internally and adds the public static modifier to expose these constant objects externally
JDK1. After 5
Simple syntax format:
Example code:
public class TestEnum { public static void main(String[] args) { Season spring = Season.SPRING; System.out.println(spring); } } enum Season{ SPRING,SUMMER,AUTUMN,WINTER }
Complex syntax format:
Sample code
public class TestEnum { public static void main(String[] args) { Season spring = Season.SPRING; System.out.println(spring); } } enum Season{ SPRING("spring"),SUMMER("summer"),AUTUMN("autumn"),WINTER("winter"); private final String description; private Season(String description){ this.description = description; } public String toString(){//Need to write manually, cannot use Generate toString() return description; } }
Requirements and characteristics of enumeration class:
- The list of constant objects of the enumeration class must be in the first line of the enumeration class. Because it is a constant, uppercase is recommended.
- If there is no other code after the constant object list, ";" It can be omitted, otherwise ";" cannot be omitted.
- The compiler provides private parameterless construction for enumeration classes by default. If the enumeration class requires parameterless construction, it does not need to be declared, and there is no need to add parameters when writing the list of constant objects,
- If the enumeration class needs a parameterized construction, it needs to manually define the private parameterized construction. The method of calling the parameterized construction is to add (argument list) after the constant object name.
- The enumeration class inherits Java. Net by default Lang. enum class, so you can't inherit other types.
- JDK1. After 5, switch supports enumeration types, and enumeration constant names can be written after case.
- If the enumeration type has other attributes, it is recommended (not necessary) that these attributes should also be declared final, because the constant object should be immutable in the logical sense.
- Enumeration classes can implement interfaces
Common methods of enumerating types
- toString(): the constant name (object name) is returned by default. You can continue to override this method manually!
- name(): returns the constant name (object name) [rarely used]
- ordinal(): returns the minor sequence number of a constant, starting from 0 by default
- values(): returns all constant objects of the enumeration class. The return type is the array type of the current enumeration. It is a static method
- valueOf(String name): gets the enumeration object according to the name of the enumeration constant object