Internal Class & API

Posted by vcv on Thu, 15 Aug 2019 16:38:56 +0200

1. Parametric transfer

Class 1.1 names as formal parameters and return values (application)

  • 1. Class names as formal parameters of methods

    The formal parameter of a method is the class name, but what is needed is the object of that class.

    What is actually passed is the object's [address value]

  • 2. Class name as return value of method

    The return value of the method is the class name, but the object of the class is actually returned.

    What is actually passed on is also the object's [address value]

  • Sample code:

    class Cat {
        public void eat() {
            System.out.println("Cats eat fish");
        }
    }
    class CatOperator {
        public void useCat(Cat c) { //Cat c = new Cat();
            c.eat();
        }
        public Cat getCat() {
            Cat c = new Cat();
            return c;
        }
    }
    public class CatDemo {
        public static void main(String[] args) {
            //Create operation class objects and call methods
            CatOperator co = new CatOperator();
            Cat c = new Cat();
            co.useCat(c);
    
            Cat c2 = co.getCat(); //new Cat()
            c2.eat();
        }
    }
    

1.2 Abstract classes as parameters and return values (Understanding)

  • Abstract classes as parameters and return values

    • The formal parameter of the method is the abstract class name, but what is needed is the subclass object of the abstract class.
    • The return value of the method is the abstract class name, but it actually returns the subclass object of the abstract class.
  • Sample code:

    abstract class Animal {
        public abstract void eat();
    }
    class Cat extends Animal {
        @Override
        public void eat() {
            System.out.println("Cats eat fish");
        }
    }
    class AnimalOperator {
        public void useAnimal(Animal a) { //Animal a = new Cat();
            a.eat();
        }
        public Animal getAnimal() {
            Animal a = new Cat();
            return a;
        }
    }
    public class AnimalDemo {
        public static void main(String[] args) {
            //Create operation class objects and call methods
            AnimalOperator ao = new AnimalOperator();
            Animal a = new Cat();
            ao.useAnimal(a);
    
            Animal a2 = ao.getAnimal(); //new Cat()
            a2.eat();
        }
    }
    

1.3 Interface Name as Formal Parameter and Return Value (Understanding)

  • Interfaces as formal parameters and return values

    • The formal parameter of the method is the name of the interface, but what is needed is the implementation class object of the interface.
    • The return value of the method is the name of the interface, but it actually returns the implementation class object of the interface.
  • Sample code:

    interface Jumpping {
        void jump();
    }
    class JumppingOperator {
        public void useJumpping(Jumpping j) { //Jumpping j = new Cat();
            j.jump();
        }
        public Jumpping getJumpping() {
            Jumpping j = new Cat();
            return j;
        }
    }
    class Cat implements Jumpping {
        @Override
        public void jump() {
            System.out.println("Cats can jump high.");
        }
    }
    public class JumppingDemo {
        public static void main(String[] args) {
            //Create operation class objects and call methods
            JumppingOperator jo = new JumppingOperator();
            Jumpping j = new Cat();
            jo.useJumpping(j);
    
            Jumpping j2 = jo.getJumpping(); //new Cat()
            j2.jump();
        }
    }
    
    

2. Internal classes

2.1 Basic Use of Internal Classes (Understanding)

  • Internal class concept

    • Define a class in a class. Example: Define a class B inside a class A, and class B is called an internal class.
  • Internal Class Definition Format

    • Format & Ex amp les:

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

    • Internal classes have direct access to members of external classes, including private ones.
    • To access members of internal classes, external classes must create objects
  • Sample code:

    /*
        Internal class access features:
            Internal classes have direct access to members of external classes, including private ones.
            To access members of internal classes, external classes must create objects
     */
    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();
        }
    }
    

2.2 Internal Classes of Members (Understanding)

  • Definition Location of Classes within Members

    • In classes, methods are positioned with member variables
  • Externally Create Members'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 scenarios for member inner classes

    • To design a class as an internal class, most of them do not want to be accessed by the outside world, so the definition of internal class should be privatized. After privatization, a method that can be called by the outside world is provided. The inner class object is created and invoked by the method.
  • Sample 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();
        }
    }
    

2.3 Local Internal Classes (Understanding)

  • Location of Local Internal Class Definition

    • Local inner classes are classes defined in methods
  • Local Internal Class Style

    • Local internal classes, which cannot be used directly from outside, need to create objects and use them within methods.
    • This class can directly access members of external classes or local variables within 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();
        }
    }
    
    

2.4 Anonymous Internal Classes (Applications)

  • Prerequisites for anonymous inner classes

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

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

    • Give an example:

      new Inter(){
          @Override
          public void method(){}
      } 
      
  • The Nature of Anonymous Internal Classes

    • Essence: An anonymous subclass object that inherits this class or implements 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(){
              
          }
      }
      
  • Invoking methods directly from anonymous inner classes

    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 invocation of methods
        }
    }
    

2.4 Use of anonymous internal classes in development (application)

  • Use of anonymous internal classes in development

    • When we find that a method needs subclass objects of interfaces or abstract classes, we can pass an anonymous inner class past to simplify the traditional code.
  • Sample code:

    interface Jumpping {
        void jump();
    }
    class Cat implements Jumpping {
        @Override
        public void jump() {
            System.out.println("Cats can jump high.");
        }
    }
    class Dog implements Jumpping {
        @Override
        public void jump() {
            System.out.println("Dogs can jump high.");
        }
    }
    class JumppingOperator {
        public void method(Jumpping j) { //new Cat();   new Dog();
            j.jump();
        }
    }
    class JumppingDemo {
        public static void main(String[] args) {
            //Requirement: 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("Cats can jump high.");
                }
            });
    		// Simplification of anonymous inner classes
            jo.method(new Jumpping() {
                @Override
                public void jump() {
                    System.out.println("Dogs can jump high.");
                }
            });
        }
    }
    

3. Common API s

3.1 Math (Application)

  • 1. Overview of Math Classes

    • Math contains methods for performing basic numeric operations
  • 2. Calling Method in Math

    • There are no constructive methods in Math classes, but the internal methods are static and can be called by class name.
  • 3. Common methods of Math classes

    Method Name Method Name Explain
    public static int abs(int a) Returns the absolute value of the parameter
    public static double ceil(double a) Returns the minimum double value greater than or equal to an integer
    public static double floor(double a) Returns the maximum double value less than or equal to the parameter, equal to an integer
    public static int round(float a) Returns the nearest parameter int by rounding
    public static int max(int a,int b) Returns the larger of the two int values
    public static int min(int a,int b) Returns the smaller of the two int values
    public static double pow (double a,double b) Returns the value of the b power of a
    public static double random() The return value is a positive value of double, [0.0, 1.0]

3.2 System (Application)

  • Common Methods of System Classes
Method name Explain
public static void exit(int status) Termination of the currently running Java Virtual Machine, non-zero indicates abnormal termination
public static long currentTimeMillis() Returns the current time (in milliseconds)
  • Sample code

    • Requirement: Output 1-10000 in the console to calculate how many milliseconds this code has been executed
    public class SystemDemo {
        public static void main(String[] args) {
            // Get the start time node
            long start = System.currentTimeMillis();
            for (int i = 1; i <= 10000; i++) {
                System.out.println(i);
            }
            // Gets the time node after the code runs
            long end = System.currentTimeMillis();
            System.out.println("Time-consuming:" + (end - start) + "Millisecond");
        }
    }
    

3.3 toString method of Object class (application)

  • Overview of Object Classes

    • Object is the root of the class hierarchy, and each class can use Object as a superclass. All classes inherit directly or indirectly from this class. In other words, all classes have a share of the methods that this class has.
  • How to view method source code

    • Select the method and press Ctrl + B
  • How to override the toString method

      1. Alt + Insert Selects toString
      1. In the blank area of the class, right-click - > Generate - > select toString
  • The role of the toString method:

  • In a good format, it is more convenient to display the attribute values in the object.

  • Sample code:

    class Student extends Object {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
    public class ObjectDemo {
        public static void main(String[] args) {
            Student s = new Student();
            s.setName("Lin Qingxia");
            s.setAge(30);
            System.out.println(s); 
            System.out.println(s.toString()); 
        }
    }
    
  • Operation results:

    Student{name='Lin Qingxia', age=30}
    Student{name='Lin Qingxia', age=30}
    

3.4 equals Method of Object Class (Application)

  • The Function of equals Method

    • For comparison between objects, return the results of true and false
    • Examples: s1. equals (s2); S1 and S2 are two objects
  • Scenarios for rewriting equals methods

    • Do not want to compare the address value of the object, when you want to compare with the object attribute.
  • How to override equals method

      1. alt + insert chooses equals() and hashCode(), IntelliJ Default, next, finish all the way.
      1. In the blank area of the class, right-click - > Generate - > select equals() and hashCode(), the same after.
  • Sample code:

    class Student {
        private String name;
        private int age;
    
        public Student() {
        }
    
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        @Override
        public boolean equals(Object o) {
            //this -- s1
            //o -- s2
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
    
            Student student = (Student) o; //student -- s2
    
            if (age != student.age) return false;
            return name != null ? name.equals(student.name) : student.name == null;
        }
    }
    public class ObjectDemo {
        public static void main(String[] args) {
            Student s1 = new Student();
            s1.setName("Lin Qingxia");
            s1.setAge(30);
    
            Student s2 = new Student();
            s2.setName("Lin Qingxia");
            s2.setAge(30);
    
            //Requirements: Compare the content of two objects to see if they are the same
            System.out.println(s1.equals(s2));
        }
    }
    
    

3.5 Bubble Sorting Principle (Understanding)

  • Overview of Bubble Sorting
    • A sort method that compares two adjacent data in the data to be sorted, places the larger data behind, and operates on all data in turn until all data are sorted according to requirements.
  • If you have n data sorted, you need to compare n-1 times in total.
  • After each comparison, one less data will be involved in the next comparison.

3.6 Bubble Sorting Code Implementation (Understanding)

  • code implementation
/*
    Bubble sort:
        A sorting method that compares the adjacent data in the data to be sorted in pairs and places the larger data behind.
        Operate all data in turn until all data is sorted as required.
 */
public class ArrayDemo {
    public static void main(String[] args) {
        //Define an array
        int[] arr = {24, 69, 80, 57, 13};
        System.out.println("Before sorting:" + arrayToString(arr));

        // Here minus 1 is to control the number of comparisons per round.
        for (int x = 0; x < arr.length - 1; x++) {
            // - 1 is to avoid index crossing, and - x is to improve comparative efficiency
            for (int i = 0; i < arr.length - 1 - x; i++) {
                if (arr[i] > arr[i + 1]) {
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                }
            }
        }
        System.out.println("After sorting:" + arrayToString(arr));

    }

    //Compose the elements of an array into a string according to the specified rules: [Element 1, Element 2,...]
    public static String arrayToString(int[] arr) {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < arr.length; i++) {
            if (i == arr.length - 1) {
                sb.append(arr[i]);
            } else {
                sb.append(arr[i]).append(", ");
            }
        }
        sb.append("]");
        String s = sb.toString();
        return s;
    }
}

3.7 Arrays (Applications)

  • Common methods of Arrays

    Method name Explain
    public static String toString(int[] a) Returns the string representation of the contents of the specified array
    public static void sort(int[] a) Arrays specified in numerical order
  • Design Idea of Tool Class

    1. private modification of construction method

    2. Members are decorated with public statistics

Topics: less Attribute Java