Internal class & & packaging class

Keywords: Java

Tip: the following is the main content of this article. The following cases can be used for reference

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.1 member internal class

  • 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();
  • Recommended usage scheme of inner class of member

    • 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();
        }
    }
    

1.2 local internal class

  • 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.3 anonymous inner class

  • 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.4 use of anonymous inner classes in development

  • 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:

    interface Jumpping {
        void jump();
    }
    class Cat implements Jumpping {
        @Override
        public void jump() {
            System.out.println("The cat can jump high");
        }
    }
    class Dog implements Jumpping {
        @Override
        public void jump() {
            System.out.println("The dog can jump high");
        }
    }
    class JumppingOperator {
        public void method(Jumpping j) { //new Cat();   new Dog();
            j.jump();
        }
    }
    class JumppingDemo {
        public static void main(String[] args) {
            //Requirements: create the object of the interface operation class and call the method method method
            JumppingOperator jo = new JumppingOperator();
            Jumpping j = new Cat();
            jo.method(j);
    
            Jumpping j2 = new Dog();
            jo.method(j2);
            System.out.println("--------");
    
            // Simplification of anonymous inner classes
            jo.method(new Jumpping() {
                @Override
                public void jump() {
                    System.out.println("The cat can jump high");
                }
            });
    		// Simplification of anonymous inner classes
            jo.method(new Jumpping() {
                @Override
                public void jump() {
                    System.out.println("The dog can jump high");
                }
            });
        }
    }
    

Packaging

Basic type packing class

  • Function of basic type packaging class

    The advantage of encapsulating a basic data type as an object is that more functional methods can be defined in the object to manipulate the data

    One of the common operations: used for conversion between basic data type and string

  • Wrapper class corresponding to basic type

    Basic data typePackaging
    byteByte
    shortShort
    intInteger
    longLong
    floatFloat
    doubleDouble
    charCharacter
    booleanBoolean

2.1 integer class

  • Overview of Integer class

    Wrap the value of the original type int in an object

  • Integer class constructor

    Method nameexplain
    public Integer(int value)Create Integer object based on int value (obsolete)
    public Integer(String s)Create Integer object based on String value (obsolete)
    public static Integer valueOf(int i)Returns an Integer instance representing the specified int value
    public static Integer valueOf(String s)Returns an Integer object String that holds the specified value
  • Sample code

    public class IntegerDemo {
        public static void main(String[] args) {
            //public Integer(int value): creates an Integer object based on the int value (obsolete)
            Integer i1 = new Integer(100);
            System.out.println(i1);
    
            //public Integer(String s): creates an Integer object based on the String value (obsolete)
            Integer i2 = new Integer("100");
    //        Integer i2 = new Integer("abc"); //NumberFormatException
            System.out.println(i2);
            System.out.println("--------");
    
            //public static Integer valueOf(int i): returns an Integer instance representing the specified int value
            Integer i3 = Integer.valueOf(100);
            System.out.println(i3);
    
            //public static Integer valueOf(String s): returns an Integer object String that holds the specified value
            Integer i4 = Integer.valueOf("100");
            System.out.println(i4);
        }
    }
    

2.2 conversion between int and String types

  • Convert int to String

    • Conversion mode

      • Method 1: add an empty string directly after the number
      • Method 2: use the String class static method valueOf()
    • Sample code

      public class IntegerDemo {
          public static void main(String[] args) {
              //int --- String
              int number = 100;
              //Mode 1
              String s1 = number + "";
              System.out.println(s1);
              //Mode 2
              //public static String valueOf(int i)
              String s2 = String.valueOf(number);
              System.out.println(s2);
              System.out.println("--------");
          }
      }
      
  • Convert String to int

    • Conversion mode

      • Method 1: first convert the string number to Integer, and then call the valueOf() method
      • Method 2: convert through Integer static method parseInt()
    • Sample code

      public class IntegerDemo {
          public static void main(String[] args) {
              //String --- int
              String s = "100";
              //Method 1: String --- Integer --- int
              Integer i = Integer.valueOf(s);
              //public int intValue()
              int x = i.intValue();
              System.out.println(x);
              //Mode 2
              //public static int parseInt(String s)
              int y = Integer.parseInt(s);
              System.out.println(y);
          }
      }
      

2.3 string data sorting cases

  • Case requirements

    There is a string: "91 27 46 38 50". Please write a program to realize it. The final output result is: "27 38 46 50 91"

  • code implementation

    public class IntegerTest {
        public static void main(String[] args) {
            //Define a string
            String s = "91 27 46 38 50";
    
            //Store the numeric data in the string into an array of type int
            String[] strArray = s.split(" ");
    //        for(int i=0; i<strArray.length; i++) {
    //            System.out.println(strArray[i]);
    //        }
    
            //Define an int array and store each element in the String [] array in the int array
            int[] arr = new int[strArray.length];
            for(int i=0; i<arr.length; i++) {
                arr[i] = Integer.parseInt(strArray[i]);
            }
    
            //Sort int array
            Arrays.sort(arr);
    
            //The elements in the sorted int array are spliced to obtain a string, which is implemented by StringBuilder
            StringBuilder sb = new StringBuilder();
            for(int i=0; i<arr.length; i++) {
                if(i == arr.length - 1) {
                    sb.append(arr[i]);
                } else {
                    sb.append(arr[i]).append(" ");
                }
            }
            String result = sb.toString();
    
            //Output results
            System.out.println(result);
        }
    }
    

2.4 automatic unpacking and automatic packing

  • Automatic packing

    Convert the basic data type to the corresponding wrapper class type

  • Automatic unpacking

    Convert the wrapper class type to the corresponding basic data type

  • Sample code

    Integer i = 100;  // Automatic packing
    i += 200;         // i = i + 200; I + 200 automatic unpacking; i = i + 200; yes automatic packing
    

Posted by dearmoawiz on Sat, 18 Sep 2021 06:26:07 -0700