Java language introduction 𞓜 02 | object oriented and common class 𞓜 day10 | interface, polymorphic

Keywords: Java Lambda Programming less

Chapter I interface

1.1 Interface Overview and life examples

  1. Interface is a common standard
    • As long as it conforms to the standard, it can be used by all

1.2 basic format of interface definition

  1. Interface is a kind of reference data type, and the most important content is abstract method.
  2. 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:

  1. If it is Java 7, the interface can include:
    1. constant
    2. Abstract method
  2. If it is Java 8, the interface includes:
    3. Static method
    4. Default method
  3. If it is Java 9, the interface includes:
    5. Private method

1.3 abstract method definition of interface

  1. 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:
    1. For an abstract method in an interface, the modifier must be two fixed Keywords: public abstract
    2. These two keyword modifiers can be omitted selectively.
    3. 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:
  1. 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{
            // ...
        }
    
  2. 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
  3. Create an object to implement the class and use it
    • Cannot be used directly by new interface object
  4. Creation Name: interface name + Impl (soft requirement)
  • matters needing attention:
    1. 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)

  1. 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)

  1. 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:
    1. Static methods in an interface cannot be called by objects of an interface implementation class.
  • Correct usage:
    1. Format:
        Interface name. Static method name (parameter);
    
    1. 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:
    1. 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.
  • resolvent:
    1. Starting with Java 9, private methods are allowed to be defined in the interface
      1. ++Common private method + +, to solve the problem of repeated code between multiple default methods
        • Format:
            private return value type method name (parameter){
                Method body
            }
        
      2. ++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
            }
        

1.10 constant definition and use of interface

  1. "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
  2. 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

  1. Precautions when using the interface:
    1. There is no static code block or constructor for an interface.
      • static {}
      • public interface name () {}
    2. 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
              
          }
      
    3. If there are duplicate abstract methods among multiple interfaces implemented by the implementation class, only one override is needed.
    4. 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 {}
      
    5. If there are duplicate default methods in multiple interfaces implemented by the implementation class, the implementation class must override the conflicting default methods
    6. 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++
  • 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

  1. Some relationships between classes and interfaces
    1. There is a single inheritance between classes. There is only one direct parent class.
    2. There are multiple implementations between classes and interfaces. A class can implement multiple interfaces.
    3. There are multiple inheritance between interfaces.
  • Note:
    1. If the abstract methods in multiple parent interfaces are repeated, it doesn't matter. (no method body [key point])
    2. 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

  1. The code embodies polymorphism, which is actually a sentence: the parent class reference points to the child class object
  2. 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

  1. Review (two ways to access member variables):
    1. 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
    
    1. 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

  1. 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
    
  1. 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

  1. 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

  1. 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
  2. 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

  1. Disadvantages of upward Transformation:
    • Once the object is transformed to the parent class, the original content of the child class cannot be called
  2. Solution:
    • Downward transformation of using objects [restore]
  3. Format:
    • Subclass name object name = (subclass name) parent class object name;
        Animal animal = new Cat();
        
        Cat cat = (Cat)animal;
    
  4. 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)
  5. matters needing attention:
    1. 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
    2. 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

  1. How to know the reference object of a parent class and what subclass it is originally
  2. 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
  3. 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
Private letter follow

Posted by nikes90 on Fri, 21 Feb 2020 04:08:02 -0800