Chapter I interface
1.1 Interface Overview and life examples
-
Interface is a common standard
- As long as it conforms to the standard, it can be used by all
- As long as it conforms to the standard, it can be used by all
1.2 basic format of interface definition
- Interface is a kind of reference data type, and the most important content is abstract method.
- Define the format of an interface:
public interface interface name{ //Interface content }
-
Note: after the keyword interface is changed, the bytecode file generated by compilation is still:. java – >. Class
-
The interface includes the following:
- If it is Java 7, the interface can include:
- constant
- Abstract method
- If it is Java 8, the interface includes:
3. Static method
4. Default method - If it is Java 9, the interface includes:
5. Private method
1.3 abstract method definition of interface
- In any version of Java, an interface can define abstract methods: (no method body)
/ / format: public abstract returns the value type method name (parameter list);
- matters needing attention:
- For an abstract method in an interface, the modifier must be two fixed Keywords: public abstract
- These two keyword modifiers can be omitted selectively.
- The three elements of the method can be defined at will
public interface MyInterfaceAbstract { //It's all abstract public abstract void methodAbs(); abstract void methodAbs1(); public void methodAbs2(); void methodAbs3(); }
1.4 use of abstract methods of interface
- Interface use steps:
- The interface cannot be used directly. There must be an implementation class to implement the interface.
/ / format: public class implementation class name implements interface name{ // ... }
- The implementation class of the interface must cover all abstract methods in the rewriting (Implementation) interface
- Implementation: remove abstract keyword and add method body brace
- Create an object to implement the class and use it
- Cannot be used directly by new interface object
- Creation Name: interface name + Impl (soft requirement)
- matters needing attention:
- If the implementation class does not cover all the abstract methods in the rewriting interface, the implementation class itself must be an abstract class
//An interface is defined: myinterfaceabtrace.java public interface MyInterfaceAbstract { //It's all abstract public abstract void methodAbs(); abstract void methodAbs1(); public void methodAbs2(); void methodAbs3(); } //An implementation class is defined: MyInterfaceAbstractImpl.java public class MyInterfaceAbstractImpl implements MyInterfaceAbstract{ @Override public void methodAbs() { System.out.println("This is the first way"); } @Override public void methodAbs1() { System.out.println("This is the second way"); } @Override public void methodAbs2() { System.out.println("This is the third way"); } @Override public void methodAbs3() { System.out.println("This is the fourth way"); } } //Main method: Demo01Interface.java public static void main(String[] args) { //Wrong //MyInterfaceAbstract inter = new MyInterfaceAbstract(); MyInterfaceAbstractImpl impl = new MyInterfaceAbstractImpl(); impl.methodAbs(); impl.methodAbs1(); }
1.5 default method definition of interface (Java 8)
- Starting from Java 8, the interface allows defining default methods: (with method body)
/ / format: public default return value type method name (parameter list){ Method body; }
- Note: the default method in the interface can solve the problem of interface upgrading (in the next course: Lambda expression and functional programming - > the default method of the interface can splice the function model)
- The original interface has only one abstract method, with many implementation classes
- At this time, the interface is adding an abstract method, and each implementation class needs to override the override
- The implementation class does not need to override the override, but also wants to add an abstract method to the interface
- So we need to use the default method – > with the default method body
1.6 default method usage of interface
- Note: public can be omitted. default cannot
- Note: the default method will be inherited by the implementation class
- matters needing attention:
- The default method of the interface, through which class objects can be implemented and directly called
- The default method of the interface can also be overridden and rewritten by the interface implementation class
- Note: the abstract method is called, and the implementation class on the right is actually running
- Note: call the default method. If there is no interface in the implementation class, the interface will be looked up
//An interface is defined: MyInterfaceDefault.java public interface MyInterfaceDefault { //Abstract method public abstract void methodAbs(); //New abstract method //public abstract void methodAbs2(); //Want to add a new method, change to the default method public default void methodDefault(){ System.out.println("This is the default method for new additions"); } } //An implementation class a is defined: MyInterfaceDefaultA.java public class MyInterfaceDefaultA implements MyInterfaceDefault { @Override public void methodAbs() { System.out.println("Abstract methods are implemented, AAA"); } } //An implementation class B is defined: myinterfacedefaultb.java public class MyInterfaceDefaultB implements MyInterfaceDefault { @Override public void methodAbs() { System.out.println("Abstract methods are implemented, BBB"); } //Override overridden methodDefault @Override public void methodDefault() { System.out.println("Implementation class B Override overrides the default method of the interface"); } } //Main method: Demo02Interface public static void main(String[] args) { MyInterfaceDefaultA a = new MyInterfaceDefaultA(); a.methodAbs(); a.methodDefault(); //This is the default method for new additions System.out.println("========="); MyInterfaceDefaultB b = new MyInterfaceDefaultB(); b.methodAbs(); b.methodDefault(); //Implementation class B overrides the default method of the interface }
1.7 static method definition of interface (Java 8)
- Format:
public static return value type method name (parameter list){ Method body }
- Tip: just change abstract or default to static, with the upper body.
1.8 static method usage of interface
- Note:
- Static methods in an interface cannot be called by objects of an interface implementation class.
- Correct usage:
- Format:
Interface name. Static method name (parameter);
- Static methods have nothing to do with objects and classes, so call methods directly with interfaces
- Direct - > interface name. Method
1.9 private method definition and use of interface (Java 9)
- Problem Description:
- We need to extract a common method to solve the problem of duplicate code between two default methods
- However, this shared method should not be used by the implementation class. It should be private.
- We need to extract a common method to solve the problem of duplicate code between two default methods
- resolvent:
- Starting with Java 9, private methods are allowed to be defined in the interface
- ++Common private method + +, to solve the problem of repeated code between multiple default methods
- Format:
private return value type method name (parameter){ Method body }
- ++Static private method + +, to solve the problem of repeated code between multiple static methods
- Format:
private static return value type method name (parameter){ Method body }
- ++Common private method + +, to solve the problem of repeated code between multiple default methods
- Starting with Java 9, private methods are allowed to be defined in the interface
1.10 constant definition and use of interface
- "Member variable" can also be defined in the interface, but it must be decorated with three keywords public static final
- In effect, this is actually the constant of the interface
- Format:
public static final data type constant name = data value;
- Note: once the final keyword is used for decoration, the description cannot be changed
- Note: for constants in the interface, public static final can be omitted
- Note: the constants in the interface must be assigned and cannot be left unchanged after assignment
- Note: the constant name of the interface should be uppercase, and multiple names should be separated by _
- int NUM = 10;
- int NUM_OF_CLASS = 20;
1.11 summary of interface contents
1.12 inherit the parent class and implement multiple interfaces
- Precautions when using the interface:
- There is no static code block or constructor for an interface.
- static {}
- public interface name () {}
- The direct parent of a class is unique, but a class can implement multiple interfaces at the same time
public class MyInterfaceImpl implements MyInterfaceA, MyInterfaceB { //Override override all abstract methods }
- If there are duplicate abstract methods among multiple interfaces implemented by the implementation class, only one override is needed.
- If the implementation class does not cover and rewrite all abstract methods in all interfaces, then the implementation class must be an abstract class.
public abstract class implementation class name implements interface name {}
- If there are duplicate default methods in multiple interfaces implemented by the implementation class, the implementation class must override the conflicting default methods
- If there is a conflict between the method in the direct parent class and the default method in the interface, the method in the parent class will be used first
- It's OK to repeat with interface abstract method - > because + + has no method body++
- There is no static code block or constructor for an interface.
- Note: the Object class is the direct or indirect parent class of all classes (only omitted by default)
public class MyInterfaceImpl ++extends Object++ implements MyInterfaceA, MyInterfaceB { //Override override all abstract methods }
- Note: from the point of view of code writing, an interface is a method used to standardize a class
1.13 multiple inheritance between interfaces
- Some relationships between classes and interfaces
- There is a single inheritance between classes. There is only one direct parent class.
- There are multiple implementations between classes and interfaces. A class can implement multiple interfaces.
- There are multiple inheritance between interfaces.
- Note:
- If the abstract methods in multiple parent interfaces are repeated, it doesn't matter. (no method body [key point])
-
If the default method in multiple parent interfaces is repeated, it is related.
- Then the sub interface must overwrite the default method with the default keyword (cannot be omitted) [key]
//An interface is defined: MyInterfaceA.java public interface MyInterfaceA { public abstract void methodA(); public abstract void common(); public default void methodDefault(){ System.out.println("AAA"); } } //An interface is defined: MyInterfaceB.java public interface MyInterfaceB { public abstract void methodB(); public abstract void common(); public default void methodDefault(){ System.out.println("BBB"); } } //An interface is defined to inherit the above two interfaces: MyInterface.java public interface MyInterface extends MyInterfaceA, MyInterfaceB { public abstract void method(); @Override default void methodDefault() { } } //Define an implementation class: MyInterfaceImpl public class MyInterfaceImpl implements MyInterface { @Override public void method() { } @Override public void methodA() { } @Override public void methodB() { } @Override public void common() { } } //Main method: demo01relationships.java public static void main(String[] args) { MyInterfaceImpl myInterface = new MyInterfaceImpl(); myInterface.methodDefault(); }
Chapter two polymorphism
2.1 overview of polymorphism
2.2 polymorphic format and use
- The code embodies polymorphism, which is actually a sentence: the parent class reference points to the child class object
- Format:
- Parent name object name = new child name ();
- Or:
- Interface name object name = new implementation class name ();
- Polymorphism: left father right son
2.3 use characteristics of member variables in polymorphism
- Review (two ways to access member variables):
- Access the member variables directly through the object name: see who is on the left side of the equal sign and who is preferred. If not, look up
Fu obj = new Zi(); //Parent class num=10 System.out.println(obj.num); //10: See who is on the left side of the generated object's equal sign and who is preferred. If not, look up
- Access the member variable indirectly through the member method: see who the method belongs to and who takes priority. If not, look up
- The subclass does not override the override, that is, the parent: 10
- Subclass override override is subclass: 20
- Member variables cannot override overrides
Define a class: Fu.java public class Fu { int num = 10; public void showNum(){ System.out.println(num); } } //Define a subclass: Zi.java public class Zi extends Fu { int num = 20; int age = 30; //On the left side of the object is the parent class, all calls cannot reach this @Override public void showNum() { System.out.println(num); } } //Main method: Demo01MultiField.java public static void main(String[] args) { Fu obj = new Zi(); System.out.println(obj.num); //10: See who is on the left side of the generated object's equal sign and who is preferred. If not, look up System.out.println("==========="); obj.showNum(); }
- Where int age = 30; / / used for the left side of the object is the parent class, all calls are less than this
2.4 use characteristics of member method in polymorphism
- In polymorphic code, the access rules of member methods are:
- If you want to see the new one, you can use it first. If you don't, you can look up
-
Pithy formula: compile to the left, run to the right (see both sides of creating object equal sign)
- Compile (an action): translate. java source code into. class bytecode
//obj.methodZi(); / / wrong. When compiling, look at the left side. The left side is Fu. There is no methodZi method in Fu, so the compilation is wrong
- Compare member variables and member methods
- Member variables: compile to the left, run to the left
- Member method: compile to the left, run to the right
//Define a class: Fu.java public class Fu { int num = 10; public void showNum(){ System.out.println(num); } public void method(){ System.out.println("Parent class method"); } public void methodFu(){ System.out.println("Parent specific methods"); } } //Define a subclass: Zi.java public class Zi extends Fu { int num = 20; int age = 30; //On the left side of the object is the parent class, all calls cannot reach this @Override public void showNum() { System.out.println(num); } } //Main method: Demo01MultiMethod.java public static void main(String[] args) { Fu obj = new Zi(); obj.method(); obj.methodFu(); //obj.methodZi(); / / wrong. When compiling, look at the left side. The left side is Fu. There is no methodZi method in Fu, so the compilation is wrong }
2.5 benefits of using polymorphism
-
No matter which subclass object is changed when new is on the right, the call method on the left side of the equal sign will not change (more flexible)
2.6 object oriented upward transformation
- In fact, the upward transformation of objects is multi-state writing:
- Format:
- Parent class name object name = new subclass name (); / / parent class reference points to subclass object
- Meaning:
- Create a child object on the right, and use the parent class in it
- Similar to: double num = 100; / / Yes, int – > double (automatic type conversion)
- Note: upward transformation must be the key point of safety
- Note: upward transformation is from small scale to large scale
//Define a parent class: Animal.java public abstract class Animal { public abstract void eat(); } //Define a subclass: Cat.java public class Cat extends Animal { @Override public void eat() { System.out.println("Cats eat fish."); } } //Main method: Demo01Main.java public static void main(String[] args) { //Parent class reference points to child class object Animal animal = new Cat(); animal.eat(); }
2.7 object oriented downward transformation
- Disadvantages of upward Transformation:
- Once the object is transformed to the parent class, the original content of the child class cannot be called
- Solution:
- Downward transformation of using objects [restore]
- Format:
- Subclass name object name = (subclass name) parent class object name;
Animal animal = new Cat(); Cat cat = (Cat)animal;
- Meaning:
- Restore the parent class object to its original child class object. (similar to: cast – > int num = (int) 10.0; yes, int num = (int)10.5; no, precision loss)
- matters needing attention:
- It must be ensured that when the object was originally created, it was the cat, so as to make a downward transformation to the cat
- If the object was not originally a cat when it was created, now it has to be transformed down to a cat
- No error is reported, but it will run abnormally
- java.lang.ClassCastException: class conversion exception
//Define a parent class: Animal.java public abstract class Animal { public abstract void eat(); } //Define a subclass: Cat.java public class Cat extends Animal { @Override public void eat() { System.out.println("Cats eat fish."); } public void catchMouse(){ System.out.println("The cat catches mice."); } } //Define another subclass: Dog.java public class Dog extends Animal { @Override public void eat() { System.out.println("Fall"); } public void watchHouse(){ System.out.println("Dog watching"); } } //Main method: Demo01Main.java public static void main(String[] args) { //Parent class reference points to child class object Animal animal = new Cat(); animal.eat(); //animal.catchMouse(); / / error, the parent class does not have this method //Downward transformation Cat cat = (Cat)animal; cat.catchMouse(); //Wrong transition down, because new is a cat //Dog dog = (Dog)animal; / / error writing, no error is reported, but an exception will be run //dog.watchHouse(); int num = (int)10.5; //No, accuracy loss System.out.println(num); }
2.8 type conversion with instanceof keyword
- How to know the reference object of a parent class and what subclass it is originally
- Format:
- Object instanceof class name
- This will result in a boolean value result, that is, to determine whether the previous object can be used as an instance of the following class name
- If you are afraid of making a wrong transition, you must use instanceof to judge
//Define a parent class: Animal.java public abstract class Animal { public abstract void eat(); } //Define a subclass: Cat.java public class Cat extends Animal { @Override public void eat() { System.out.println("Cats eat fish."); } public void catchMouse(){ System.out.println("The cat catches mice."); } } //Define a subclass: Dog.java public class Dog extends Animal { @Override public void eat() { System.out.println("Fall"); } public void watchHouse(){ System.out.println("Dog watching"); } } //Main method: Demo02Instanceof public class Demo02Instanceof { public static void main(String[] args) { Animal animal = new Cat(); animal.eat(); giveMeAnAnimal(new Dog()); } public static void giveMeAnAnimal(Animal animal){ //If you want to call subclass specific methods, you need to transition down //Judge whether the parent class references animal as Dog if(animal instanceof Dog){ Dog dog = (Dog) animal; dog.watchHouse(); } //Let's see if animal was Cat if(animal instanceof Cat){ Cat cat = (Cat) animal; cat.catchMouse(); } } }
- Result:
- Cats eat fish.
- Dog watching
2.9 USB interface case of notebook
2.9 USB interface case of notebook
//Define an interface USB.java public interface USB { //Because I don't know what device is on, I use abstract public abstract void open(); //open device public abstract void close(); //Shut down equipment } //Define a notebook class: Computer.java public class Computer { public void powerOn(){ System.out.println("Laptop on"); } public void powerOff(){ System.out.println("Laptop shutdown"); } //Method using USB device, using interface as parameter of method public void userDevice(USB usb){ usb.open(); //open device if(usb instanceof Mouse){ //Determine whether the left object can be used as an instance of the following class name Mouse mouse = (Mouse) usb; //Downward transformation mouse.click(); }else if(usb instanceof Keyboard){ //Don't omit it here, because it's not necessarily only mouse and keyboard, but also printer Keyboard keyboard = (Keyboard) usb; keyboard.type(); } usb.close(); //Shut down equipment } } //Define a mouse implementation class: Mouse.java public class Mouse implements USB { @Override public void open() { System.out.println("Open mouse"); } @Override public void close() { System.out.println("Close mouse"); } public void click(){ System.out.println("Mouse click"); } } //Define a keyboard implementation class: Keyboard.java public class Keyboard implements USB { @Override public void open() { System.out.println("Open keyboard"); } @Override public void close() { System.out.println("turn off keyboard"); } public void type(){ System.out.println("Keyboard entry"); } } //Main method: DemoMain.java public static void main(String[] args) { Computer computer = new Computer(); computer.powerOn(); //Prepare a mouse for your computer (first up) USB usbMouse = new Mouse(); //Polymorphism (first) computer.userDevice(usbMouse); //Prepare a keyboard Keyboard usbKeyboard = new Keyboard(); //No polymorphism used (second) //The parameter is a USB type, and the object passed in is the implementation class object computer.userDevice(usbKeyboard); //There has also been an upward transformation //Use subclass objects, anonymous objects, or (third) //computer.userDevice(new Keyboard()); / / you can also computer.powerOff(); }
Published 10 original articles, won praise 4, visited 110