Introduction to JAVA -- internal classes and Lambda expressions

Posted by langer on Sun, 12 Sep 2021 09:42:59 +0200

1. Internal class

1.1 basic use of internal classes (understanding)

  • Inner class concept

    • Define a class in a class. For example, if a class B is defined inside a Class A, class B is called an inner class
  • Internal class definition format

    • Format & ex amp le:

      /*
      	Format:
          class External class name{
          	Modifier class internal class name{
          	
          	}
          }
      */
      
      class Outer {
          public class Inner {
              
          }
      }
      
  • Access characteristics of internal classes

    • Internal classes can directly access members of external classes, including private classes
    • An object must be created for an external class to access members of an internal class
  • Example code:

    /*
        Internal class access features:
            Internal classes can directly access members of external classes, including private classes
            An object must be created for an external class to access members of an internal class
     */
    public class Outer {
        private int num = 10;
        public class Inner {
            public void show() {
                System.out.println(num);
            }
        }
        public void method() {
            Inner i = new Inner();
            i.show();
        }
    }
    

1.2 member internal class (understanding)

  • The definition location of the class inside the member

    • In a class, a method is in the same place as a member variable
  • External member internal class format

    • Format: external class name. Internal class name object name = external class object. Internal class object;
    • Example: Outer.Inner oi = new Outer().new Inner();
  • Private member inner class

    • For the purpose of designing a class as an internal class, most of them do not want to be accessed by the outside world, so the definition of the internal class should be privatized. After privatization, a method that can be called by the outside world is provided. The internal class object is created and called inside the method.

    • Example code:

      class Outer {
          private int num = 10;
          private class Inner {
              public void show() {
                  System.out.println(num);
              }
          }
          public void method() {
              Inner i = new Inner();
              i.show();
          }
      }
      public class InnerDemo {
          public static void main(String[] args) {
      		//Outer.Inner oi = new Outer().new Inner();
      		//oi.show();
              Outer o = new Outer();
              o.method();
          }
      }
      
  • Static member inner class

    • Static member internal class access format: external class name. Internal class name object name = new external class name. Internal class name ();

    • Static methods in internal classes of static members: external class name. Internal class name. Method name ();

    • Sample code

      class Outer {
          static class Inner {
              public void show(){
                  System.out.println("inner..show");
              }
      
              public static void method(){
                  System.out.println("inner..method");
              }
          }
      }
      
      public class Test3Innerclass {
          /*
              Static member inner class demo
           */
          public static void main(String[] args) {
              // External class name. Internal class name object name = new external class name. Internal class name ();
              Outer.Inner oi = new Outer.Inner();
              oi.show();
      
              Outer.Inner.method();
          }
      }
      

1.3 local internal classes (understanding)

  • Local internal class definition location

    • A local inner class is a class defined in a method
  • Local internal class mode

    • Local internal classes cannot be used directly by the outside world. You need to create objects inside the method and use them
    • This class can directly access members of external classes or local variables in methods
  • Sample code

    class Outer {
        private int num = 10;
        public void method() {
            int num2 = 20;
            class Inner {
                public void show() {
                    System.out.println(num);
                    System.out.println(num2);
                }
            }
            Inner i = new Inner();
            i.show();
        }
    }
    public class OuterDemo {
        public static void main(String[] args) {
            Outer o = new Outer();
            o.method();
        }
    }
    
    

1.4 anonymous inner class (application)

  • Premise of anonymous inner class

    • There is a class or interface, where the class can be concrete or abstract
  • Format of anonymous inner class

    • Format: new class name () {rewrite method} new interface name () {rewrite method}

    • give an example:

      new Inter(){
          @Override
          public void method(){}
      } 
      
  • The nature of anonymous inner classes

    • Essence: it is an anonymous object that inherits the class or implements the subclass of the interface
  • Details of anonymous inner classes

    • Anonymous inner classes can be accepted in the form of polymorphism

      Inter i = new Inter(){
        @Override
          public void method(){
              
          }
      }
      
  • Anonymous inner classes call methods directly

    interface Inter{
        void method();
    }
    
    class Test{
        public static void main(String[] args){
            new Inter(){
                @Override
                public void method(){
                    System.out.println("I am an anonymous inner class");
                }
            }.method();	// Direct call method
        }
    }
    

1.5 use of anonymous inner classes in development (application)

  • Use of anonymous inner classes in development

    • When a method needs a subclass object of an interface or abstract class, we can pass an anonymous inner class to simplify the traditional code
  • Example code:

    /*
        Swimming interface
     */
    interface Swimming {
        void swim();
    }
    
    public class TestSwimming {
        public static void main(String[] args) {
            goSwimming(new Swimming() {
                @Override
                public void swim() {
                    System.out.println("Iron juice, Let's go swimming");
                }
            });
        }
    
        /**
         * Methods of using interfaces
         */
        public static void goSwimming(Swimming swimming){
            /*
                Swimming swim = new Swimming() {
                    @Override
                    public void swim() {
                        System.out.println("Iron juice, let's go swimming ");
                    }
                }
             */
            swimming.swim();
        }
    }
    
    

2.Lambda expression

2.1 experience Lambda expression [understanding]

  • Code demonstration

    /*
        Swimming interface
     */
    interface Swimming {
        void swim();
    }
    
    public class TestSwimming {
        public static void main(String[] args) {
            // Implemented through anonymous inner classes
            goSwimming(new Swimming() {
                @Override
                public void swim() {
                    System.out.println("Iron juice, Let's go swimming");
                }
            });
    
            /*  Implemented by Lambda expression
                Understanding: for Lambda expressions, anonymous inner classes are optimized
             */
            goSwimming(() -> System.out.println("Iron juice, Let's go swimming"));
        }
    
        /**
         * Methods of using interfaces
         */
        public static void goSwimming(Swimming swimming) {
            swimming.swim();
        }
    }
    
    
  • Overview of functional programming ideas

    In mathematics, a function is a set of calculation schemes with input and output, that is, "taking data for operation"

    Object oriented thought emphasizes that "things must be done in the form of objects"

    Functional thinking tries to ignore the complex object-oriented syntax: "emphasize what to do, not what form to do"

    The Lambda expression we want to learn is the embodiment of the idea of functional expression

2.2 standard format of lambda expression [understanding]

  • Format:

    (formal parameter) - > {code block}

    • Formal parameters: if there are multiple parameters, the parameters are separated by commas; if there are no parameters, leave blank
    • ->: it is composed of a line drawn in English and the greater than symbol. It is written in a fixed way. It represents pointing action
    • Code block: it is the specific thing we need to do, that is, the content of the method body we wrote before
  • Three elements that make up a Lambda expression:

    • Formal parameter, arrow, code block

2.3 lambda expression exercise 1 [application]

  • Premise of Lambda expression

    • There is an interface
    • There is only one abstract method in the interface
  • Exercise description

    Practice of parameter free and return value free abstract method

  • Operation steps

    • Define an interface (Eatable), which defines an abstract method: void eat();
    • Define a test class (EatableDemo) and provide two methods in the test class
      • One method is: use eatable (eatable E)
      • One method is the main method, and the useEatable method is called in the main method.
  • Sample code

    //Interface
    public interface Eatable {
        void eat();
    }
    //Implementation class
    public class EatableImpl implements Eatable {
        @Override
        public void eat() {
            System.out.println("An apple a day keeps the doctor away");
        }
    }
    //Test class
    public class EatableDemo {
        public static void main(String[] args) {
            //Calling the useEatable method in the main method
            Eatable e = new EatableImpl();
            useEatable(e);
    
            //Anonymous Inner Class 
            useEatable(new Eatable() {
                @Override
                public void eat() {
                    System.out.println("An apple a day keeps the doctor away");
                }
            });
    
            //Lambda expression
            useEatable(() -> {
                System.out.println("An apple a day keeps the doctor away");
            });
        }
    
        private static void useEatable(Eatable e) {
            e.eat();
        }
    }
    
    

2.4 lambda expression exercise 2 [application]

  • Exercise description

    Exercises on abstract methods with parameters and no return values

  • Operation steps

    • Define an interface (Flyable), which defines an abstract method: void fly(String s);
    • Define a test class (FlyableDemo) and provide two methods in the test class
      • One method is: use flyable (flyable f)
      • One method is the main method, and the useFlyable method is called in the main method.
  • Sample code

    public interface Flyable {
        void fly(String s);
    }
    
    public class FlyableDemo {
        public static void main(String[] args) {
            //Calling the useFlyable method in the main method
            //Anonymous Inner Class 
            useFlyable(new Flyable() {
                @Override
                public void fly(String s) {
                    System.out.println(s);
                    System.out.println("Plane self driving tour");
                }
            });
            System.out.println("--------");
    
            //Lambda
            useFlyable((String s) -> {
                System.out.println(s);
                System.out.println("Plane self driving tour");
            });
    
        }
    
        private static void useFlyable(Flyable f) {
            f.fly("The wind is sunny and the sky is clear");
        }
    }
    
    

2.5 lambda expression exercise 3 [application]

  • Exercise description

    Exercises on abstract methods with parameters and return values

  • Operation steps

    • Define an interface (Addable), which defines an abstract method: int add(int x,int y);
    • Define a test class (AddableDemo) and provide two methods in the test class
      • One method is: use addable (addable a)
      • One method is the main method, and the useAddable method is called in the main method.
  • Sample code

    public interface Addable {
        int add(int x,int y);
    }
    
    public class AddableDemo {
        public static void main(String[] args) {
            //Calling the useAddable method in the main method
            useAddable((int x,int y) -> {
                return x + y;
            });
    
        }
    
        private static void useAddable(Addable a) {
            int sum = a.add(10, 20);
            System.out.println(sum);
        }
    }
    
    

2.6 omission mode of lambda expression [application]

  • Omitted rules

    • Parameter types can be omitted. However, when there are multiple parameters, only one cannot be omitted
    • If there is only one parameter, the parentheses can be omitted
    • If the code block has only one statement, you can omit braces, semicolons, and the return keyword
  • Code demonstration

    public interface Addable {
        int add(int x, int y);
    }
    
    public interface Flyable {
        void fly(String s);
    }
    
    public class LambdaDemo {
        public static void main(String[] args) {
    //        useAddable((int x,int y) -> {
    //            return x + y;
    //        });
            //The type of parameter can be omitted
            useAddable((x, y) -> {
                return x + y;
            });
    
    //        useFlyable((String s) -> {
    //            System.out.println(s);
    //        });
            //If there is only one parameter, the parentheses can be omitted
    //        useFlyable(s -> {
    //            System.out.println(s);
    //        });
    
            //If the code block has only one statement, you can omit braces and semicolons
            useFlyable(s -> System.out.println(s));
    
            //If there is only one statement in the code block, you can omit braces and semicolons. If there is a return, return should also be omitted
            useAddable((x, y) -> x + y);
        }
    
        private static void useFlyable(Flyable f) {
            f.fly("The wind is sunny and the sky is clear");
        }
    
        private static void useAddable(Addable a) {
            int sum = a.add(10, 20);
            System.out.println(sum);
        }
    }
    
    

2.7 premise of lambda expression [understanding]

  • You must have an interface to use Lambda
  • And there is only one abstract method in the interface

2.8 differences between lambda expressions and anonymous inner classes [understanding]

  • Different types required
    • Anonymous inner class: it can be an interface, an abstract class, or a concrete class
    • Lambda expression: can only be an interface
  • Different use restrictions
    • If there is only one abstract method in the interface, you can use Lambda expressions or anonymous inner classes
    • If there is more than one abstract method in the interface, only anonymous inner classes can be used, not Lambda expressions
  • Different implementation principles
    • Anonymous inner class: after compilation, a separate. Class bytecode file is generated
    • Lambda expression: after compilation, there is no separate. class bytecode file. The corresponding bytecode will be generated dynamically during operation

Topics: Java Big Data