Advanced basic JAVA -- interface and polymorphism

1. Interface

1.1 collection improvement (application) of information management system

  • Disadvantages of using array containers

    1. The container length is fixed and cannot be automatically increased according to the added function
    2. There is no method to delete, modify or query
  • Optimization steps

    1. Create a new StudentDao class, OtherStudentDao

    2. Create an ArrayList collection container object

    3. The method declaration in OtherStudentDao needs to be consistent with StudentDao

      Note: if it is inconsistent, the code in StudentService needs to be modified

    4. Improvement method (add, delete, modify, view)

    5. Replace Dao object in StudentService

  • code implementation

    OtherStudentDao class

    public class OtherStudentDao {
        // Collection container
        private static ArrayList<Student> stus = new ArrayList<>();
    
        static {
            Student stu1 = new Student("heima001","Zhang San","23","1999-11-11");
            Student stu2 = new Student("heima002","Li Si","24","2000-11-11");
    
            stus.add(stu1);
            stus.add(stu2);
        }
    
        // Add student method
        public boolean addStudent(Student stu) {
           stus.add(stu);
           return true;
        }
    
        // View student methods
        public Student[] findAllStudent() {
    
            Student[] students = new Student[stus.size()];
    
            for (int i = 0; i < students.length; i++) {
                students[i] = stus.get(i);
            }
    
            return students;
        }
    
        public void deleteStudentById(String delId) {
            // 1. Find the index position of the id in the container
            int index = getIndex(delId);
            stus.remove(index);
        }
    
        public int getIndex(String id){
            int index = -1;
            for (int i = 0; i < stus.size(); i++) {
                Student stu = stus.get(i);
                if(stu != null && stu.getId().equals(id)){
                    index = i;
                    break;
                }
            }
            return index;
        }
    
        public void updateStudent(String updateId, Student newStu) {
            // 1. Find updateId and the index position in the container
            int index = getIndex(updateId);
            stus.set(index, newStu);
        }
    }
    

    StudentService class

    public class StudentService {
        // Create StudentDao (Library)
         private OtherStudentDao studentDao = new OtherStudentDao();
      	// Other methods have not changed, which is omitted here
    }    
    

1.2 information management system extraction Dao (application)

  • Optimization steps

    1. Extract the method upward to extract a parent class (basestatentdao)
    2. The function implementation of method cannot be given in the parent class, which is defined as abstract method
    3. Let the two classes inherit basestatentdao and override the internal abstract method
  • code implementation

    BaseStudentDao class

    public abstract class BaseStudentDao {
        // Add student method
        public abstract boolean addStudent(Student stu);
        // View student methods
        public abstract Student[] findAllStudent();
        // Delete student method
        public abstract void deleteStudentById(String delId);
        // Find index method based on id
        public abstract int getIndex(String id);
        // Modify student methods
        public abstract void updateStudent(String updateId, Student newStu);
    }
    

    StudentDao class

    public class StudentDao extends BaseStudentDao {
      // Other contents remain unchanged and are omitted here
    }
    

    OtherStudentDao class

    public class OtherStudentDao extends BaseStudentDao {
      // Other contents remain unchanged and are omitted here
    }
    

1.3 Interface Overview (understanding)

  • Interface is a public standard. As long as it conforms to the standard, everyone can use it.
  • Two meanings of interface in Java
    1. Used to define specifications
    2. Used to expand functions

1.4 interface characteristics (memory)

  • The interface is decorated with the keyword interface

    public interface Interface name {} 
    
  • The class implementation interface is represented by implements

    public class Class name implements Interface name {}
    
  • Interface cannot be instantiated

    We can create the implementation class object of the interface

  • Subclass of interface

    Or override all abstract methods in the interface

    Either subclasses are abstract classes

1.5 interface member characteristics (memory)

  • Member characteristics

    • Member variable

      Can only be constant
      Default modifier: public static final

    • Construction method

      No, because the interface mainly extends functions, but does not exist

    • Member method

      Can only be abstract methods

      Default modifier: public abstract

      As for the methods in the interface, JDK8 and JDK9 have some new features, which will be explained later

  • Code demonstration

    • Interface
    public interface Inter {
        public static final int NUM = 10;
    
        public abstract void show();
    }
    
    • Implementation class
    class InterImpl implements Inter{
    
        public void method(){
            // NUM = 20;
            System.out.println(NUM);
        }
    
        public void show(){
    
        }
    }
    
    
    • Test class
    public class TestInterface {
        /*
            Member variable: can only be constant. Three keywords will be added by default
                        public static final
            Construction method: None
            Member methods: can only be abstract methods. The system will add two keywords by default
                        public abstract
         */
        public static void main(String[] args) {
            System.out.println(Inter.NUM);
        }
      
    }
    
    

1.6 relationship between class and interface (memory)

  • Relationship between classes

    Inheritance relationship can only be inherited in single layer, but it can be inherited in multiple layers

  • Relationship between class and interface

    The implementation relationship can be implemented alone or multiple, and multiple interfaces can be implemented while inheriting a class

  • Relationship between interfaces

    Inheritance relationship can be single inheritance or multiple inheritance

1.7 interface improvement (application) of information management system

  • Implementation steps

    1. Improve basestatentdao to an interface
    2. Let StudentDao and OtherStudentDao implement this interface
  • code implementation

    BaseStudentDao interface

    public interface BaseStudentDao {
        // Add student method
        public abstract boolean addStudent(Student stu);
        // View student methods
        public abstract Student[] findAllStudent();
        // Delete student method
        public abstract void deleteStudentById(String delId);
        // Find index method based on id
        public abstract int getIndex(String id);
        // Modify student methods
        public abstract void updateStudent(String updateId, Student newStu);
    }
    
    

    StudentDao class

    public class StudentDao implements BaseStudentDao {
      // Other contents remain unchanged and are omitted here
    }
    
    

    OtherStudentDao class

    public class OtherStudentDao implements BaseStudentDao {
      // Other contents remain unchanged and are omitted here
    }
    
    

1.8 decoupling improvement of information management system (application)

  • Implementation steps

    1. Create a factory package and create StudentDaoFactory (factory class)
    2. Provide static modified getStudentDao method, which is used to create StudentDao object and return
  • code implementation

    StudentDaoFactory class

    public class StudentDaoFactory {
        public static OtherStudentDao getStudentDao(){
            return new OtherStudentDao();
        }
    }
    
    

    StudentService class

    public class StudentService {
        // Create StudentDao (Library)
        // private OtherStudentDao studentDao = new OtherStudentDao();
    
        // Get the library management object through the student library management factory class
        private OtherStudentDao studentDao = StudentDaoFactory.getStudentDao();
    }  
    
    

2. Interface composition update

2.1 overview of interface composition update [understanding]

  • constant

    public static final

  • Abstract method

    public abstract

  • Default method (Java 8)

  • Static method (Java 8)

  • Private method (Java 9)

2.2 default method in interface [ application ]

  • format

    public default return value type method name (parameter list) {}

  • effect

    Solve the problem of interface upgrade

  • example

    public default void show3() { 
    }
    
    
  • matters needing attention

    • The default method is not an abstract method, so it is not forced to be overridden. But it can be rewritten. When rewriting, remove the default keyword
    • public can be omitted, but default cannot be omitted
    • If multiple interfaces are implemented and the same method declaration exists in multiple interfaces, the subclass must override the method

2.3 static method in interface [ application ]

  • format

    public static return value type method name (parameter list) {}

  • example

    public static void show() {
    }
    
    
  • matters needing attention

    • Static methods can only be called through the interface name, not through the implementation class name or object name
    • public can be omitted, but static cannot be omitted

2.4 private method in interface [application]

  • Causes of private methods

    The private method with method body is added in Java 9, which actually lays the groundwork in Java 8: Java 8 allows the default method and static method with method body to be defined in the interface. This may lead to a problem: when two default methods or static methods contain the same code implementation, the program must consider extracting this implementation code into a common method, and this common method does not need to be used by others. Therefore, it is necessary to hide it with private. This is the necessity of adding private methods in Java 9

  • Define format

    • Format 1

      private return value type method name (parameter list) {}

    • Example 1

      private void show() {  
      }
      
      
    • Format 2

      private static return value type method name (parameter list) {}

    • Example 2

      private static void method() {  
      }
      
      
  • matters needing attention

    • The default method can call private static and non static methods
    • Static methods can only call private static methods

3. Polymorphism

3.1 overview of polymorphism (memory)

  • What is polymorphism

    The same object shows different forms at different times

  • Polymorphic premise

    • There should be inheritance or implementation relationship
    • There should be method rewriting
    • A parent class reference should point to a child class object
  • Code demonstration

    class Animal {
        public void eat(){
            System.out.println("Animals eat");
        }
    }
    
    class Cat extends Animal {
        @Override
        public void eat() {
            System.out.println("Cats eat fish");
        }
    }
    
    public class Test1Polymorphic {
        /*
            Prerequisites for polymorphism:
    
                1. There should be (inheritance \ Implementation) relationship
                2. There must be a way to rewrite
                3. To have a parent class reference, point to a child class object
         */
        public static void main(String[] args) {
            // The current thing is a cat
            Cat c = new Cat();
            // The current thing is an animal
            Animal a = new Cat();
            a.eat();
    
        }
    }
    
    

3.2 member access characteristics in polymorphism (memory)

  • Member access characteristics

    • Member variable

      Compile to see the parent class, run to see the parent class

    • Member method

      Compile to see the parent class, run to see the child class

  • Code demonstration

    class Fu {
        int num = 10;
    
        public void method(){
            System.out.println("Fu.. method");
        }
    }
    
    class Zi extends Fu {
        int num = 20;
    
        public void method(){
            System.out.println("Zi.. method");
        }
    }
    
    public class Test2Polymorpic {
        /*
             Polymorphic member access characteristics:
    
                    Member variable: compile to the left (parent class), run to the left (parent class)
    
                    Member method: compile to the left (parent class) and run to the right (child class)
         */
        public static void main(String[] args) {
            Fu f = new Zi();
            System.out.println(f.num);
            f.method();
        }
    }
    
    

3.3 benefits and disadvantages of polymorphism (memory)

  • benefit

    Improve the scalability of the program. When defining a method, the parent type is used as a parameter. When using, the specific subtype is used to participate in the operation

  • malpractice

    Unique members of subclasses cannot be used

3.4 transformation in polymorphism (application)

  • Upward transformation

    A parent class reference to a child class object is an upward transformation

  • Downward transformation

    Format: subtype object name = (subtype) parent class reference;

  • Code demonstration

    class Fu {
        public void show(){
            System.out.println("Fu..show...");
        }
    }
    
    class Zi extends Fu {
        @Override
        public void show() {
            System.out.println("Zi..show...");
        }
    
        public void method(){
            System.out.println("I am a subclass specific method, method");
        }
    }
    
    public class Test3Polymorpic {
        public static void main(String[] args) {
            // 1. Upward Transformation: the parent class reference points to the child class object
            Fu f = new Zi();
            f.show();
            // The disadvantage of polymorphism: you can't call subclass specific members
            // f.method();
    
            // A: Create subclass objects directly
            // B: Downward transformation
    
            // 2. Downward Transformation: from parent type to child type
            Zi z = (Zi) f;
            z.method();
        }
    }
    
    

3.5 risks and solutions in multi state transformation (application)

  • risk

    If the actual type and the target type of the transferred reference type variable are not the same type, ClassCastException will appear during conversion

  • Solution

    • keyword

      instanceof

    • Use format

      Variable name instanceof type

      Popular understanding: judge whether the variable on the left of the keyword is the type on the right, and return the boolean result

  • Code demonstration

    abstract class Animal {
        public abstract void eat();
    }
    
    class Dog extends Animal {
        public void eat() {
            System.out.println("Dogs eat meat");
        }
    
        public void watchHome(){
            System.out.println("Housekeeping");
        }
    }
    
    class Cat extends Animal {
        public void eat() {
            System.out.println("Cats eat fish");
        }
    }
    
    public class Test4Polymorpic {
        public static void main(String[] args) {
            useAnimal(new Dog());
            useAnimal(new Cat());
        }
    
        public static void useAnimal(Animal a){  // Animal a = new Dog();
                                                 // Animal a = new Cat();
            a.eat();
            //a.watchHome();
    
    //        Dog dog = (Dog) a;
    //        dog.watchHome();  // ClassCastException type conversion exception
          
            // Judge whether the type of a variable record is Dog
            if(a instanceof Dog){
                Dog dog = (Dog) a;
                dog.watchHome();
            }
        }
    
    }
    
    

3.6 information management system improvement (application)

  • Implementation steps

    1. The return value of the method in the StudentDaoFactory class is defined as the parent class type basestatentdao
    2. The type that receives the return value of the method in StudentService is defined as the parent type basestatentdao
  • code implementation

    StudentDaoFactory class

    public class StudentDaoFactory {
        public static BaseStudentDao getStudentDao(){
            return new OtherStudentDao();
        }
    }
    
    

    StudentService class

    public class StudentService {
        // Create StudentDao (Library)
        // private OtherStudentDao studentDao = new OtherStudentDao();
    
        // Get the library management object through the student library management factory class
        private BaseStudentDao studentDao = StudentDaoFactory.getStudentDao();
    }  
    
    

Tags: Java

Posted on Sun, 12 Sep 2021 00:42:50 -0400 by Chris_Evans