Interface, polymorphism, internal class

Posted by cryp7 on Sun, 19 Dec 2021 14:12:42 +0100

Chapter I interface

Overview: an interface is a reference type in the Java language and a "collection" of methods. Therefore, the interior of the interface mainly defines methods, including constants, abstract methods (JDK 7 and before), default methods and static methods (JDK 8), and private methods (jdk9).

Interface, which is similar to defining classes, but uses the interface keyword. It will also be compiled into Class file, but it must be clear that it is not a class, but another reference data type.

public class class name java–>. class

public interface interface name java–>. class

Reference data types: array, class, interface.

For the use of an interface, it cannot create an object, but can be implemented (similar to inherited). A class that implements an interface (which can be regarded as a subclass of the interface) needs to implement all abstract methods in the interface. After creating this class object, you can call the method, otherwise it must be an abstract class.

Summary:

  • Interface is a reference type in the Java language,
  • The interface is mainly used to define methods:
    • jdk7 and before: constants, abstract methods
    • jdk8: add additional default method and static method
    • jdk9 and above: additional private methods added
  • The interface is defined using the interface keyword, and the class file will also be generated after compilation
  • An interface cannot create an object. It needs to implement interfaces. The class that implements the interface is called an implementation class (a subclass of the interface)
    • Implementation class: ordinary classes must override abstract methods in interfaces
    • Implementation class; Abstract classes do not need to override abstract methods in interfaces

Knowledge points – 3.2 definition format

format

public interface Interface name {
    // Constant (jdk7)
    // Abstract method (jdk7)
    // Default method (jdk8)
    // Static method (jdk8)
    // Private method (jdk9)
}

case

public interface IA {
    // Constant (jdk7): the modifier is public static final. These three keywords can be omitted without writing
    public static final int NUM = 10;

    // Abstract method (jdk7): the modifier is public abstract. These two keywords can be omitted without writing
    public abstract void method1();

    // Default method (jdk8): the modifier is public default. Only public can be omitted without writing
    public default void method2() {
        System.out.println("IA Default method method2");
    }

    // Static method (jdk8): the modifier is public static. Only public can be omitted without writing
    public static void method3() {
        System.out.println("IA Static method method3");
    }

    // Private method (jdk9): the modifier is private and cannot be omitted
    private void method4() {
        System.out.println("IA Private non static method method4");
    }

    private static void method5() {
        System.out.println("IA Private static method method5");
    }
}

Knowledge points – 3.3 implementation interface

Implementation overview

The relationship between class and interface is implementation relationship, that is, class implements interface. This class can be called implementation class of interface or subclass of * * interface** The implemented actions are similar to inheritance and the format is similar, but the keywords are different. The implementation uses the implements keyword.

Implementation format
  • Class can implement one interface or multiple interfaces at the same time.

    • After the class implements the interface, it must override all abstract methods in the interface, otherwise the class must be an "abstract class".

      public interface IA{
          public void show1();
      }
      public interface IB{
          public void show2();
      }
      public class Zi implements IA ,IB{
          public void show1(){
          }
          public void show2(){
          }
      }
      
  • Class can implement one or more interfaces while "inheriting a class";

    public class Fu{}
    public interface IA{}
    public interface IB{}
    public class Zi extends Fu implements IA,IB{//You must inherit first and then implement
    }
    
    

Knowledge points – 3.4 access characteristics of members in the interface

Overview of member access characteristics in interface
  Access characteristics of members in interface:
                Constants in interface: It is mainly for direct use of the interface
                Abstract methods in interfaces: For implementation class overrides
                Default method in interface: It can be overridden or called directly by the implementation class
                Static methods in interfaces: Only for direct interface call,The implementation class cannot inherit
                Private method in interface: Can only be called directly in the interface,The implementation class cannot inherit
Case demonstration
public interface IA {
    // constant
    public static final int NUM = 10;

    // Abstract method
    public abstract void method1();

    // Default method
    public default void method2(){
        System.out.println("IA Default method for interface method2...");
        method4();// Calling a non static private method
        method5();// Call static private method
    }

    // Static method
    public static void method3(){
        System.out.println("IA Static method of interface method3...");
        method5();// Call static private method
    }
    
    // Private method
    private void method4(){
        System.out.println("IA Private method of interface method4...");
    }

    private static void method5(){
        System.out.println("IA Private method of interface method5...");
    }
}

class Imp implements IA {

    @Override
    public void method1() {
        System.out.println("Implement abstract methods in class rewriting interfaces method1");
    }

    @Override
    public void method2() {
        System.out.println("Implement the default method in the class override interface method2");
    }
}

public class Test {
    public static void main(String[] args) {
        /*
            Access characteristics of members in the interface:
                Constant: mainly used for direct interface access
                Abstract method: it is mainly used to implement class rewriting
                Default method: it is mainly used for overriding or calling the implementation class directly
                Static method: it is only directly accessed by the interface
                Private method: can only be accessed directly inside the interface
         */
        System.out.println(IA.NUM);// 10

        // Create an implementation class object
        Imp imp = new Imp();
        // Constants that implement class object providers
        // System.out.println(imp.NUM);// 10

        // Abstract methods that implement class object call overrides
        // imp.method1();

        // Implement the default method of the class object call interface
        // imp.method2();

        // Static methods that implement class object call interfaces
        //imp.method3();//  Compilation reports an error, and the implementation class cannot directly access the static method of the interface
        //Imp.method3();//  Compilation reports an error, and the implementation class cannot directly access the static method of the interface

        // The interface name directly accesses the static method of the interface
        IA.method3();
    }
}

Knowledge points – several conflicts in 3.5 multi implementation

  • Conflict of public static constants
  • Conflict of public abstract methods
  • Conflict of public default methods
  • Conflict of public static methods
  • Conflict of private methods
Conflict of public static constants
  • The implementation class does not inherit conflicting variables
interface IA{
    public static final int a = 10;
    public static final int b= 20;
}
interface IB{
    public static final int a = 30;
}
class Zi implements IA,IB{
    //Only inherited b, not a, because a conflicts
}

public class Demo {
    public static void main(String[] args) {
        Zi z = new Zi();
     //   System.out.println(z.a);// Compilation error
        System.out.println(z.b);
    }
}

Conflict of public abstract methods
  • The implementation class only needs to override one
interface IA{
    public void show();
}
interface IB{
    public void show();
}
class Zi implements IA,IB{
    @Override
    public void show() {//Subclasses only need to override a show()
        System.out.println("Subclass show()...");
    }
}
public class Demo {
    public static void main(String[] args) {
        Zi z = new Zi();
        z.show();
    }
}
Conflict of public default methods
  • The implementation class must override the final version once
interface IA{
    public default void show(){
        System.out.println("IA");
    }
}
interface IB{
    public default void show(){
        System.out.println("IB");
    }
}
class Zi implements IA,IB{
    @Override
    public void show() {//show() that must be overridden once
        System.out.println("Zi of show()....");
    }
}
public class Demo {
    public static void main(String[] args) {
        Zi z = new Zi();
        z.show();
    }
}

Conflict of public static methods
  • Static methods directly belong to the interface and cannot be inherited, so there is no conflict

    interface IA{
        public static  void show(){
            System.out.println("IA");
        }
    }
    interface IB{
        public static void show(){
            System.out.println("IB");
        }
    }
    class Zi implements IA,IB{
    
    }
    public class Demo {
        public static void main(String[] args) {
            Zi z = new Zi();
            z.show();//Compilation error, show() cannot be inherited.
        }
    }
    
    
    
Conflict of private methods
  • Private methods can only be used directly in this interface without conflict

Knowledge points – 3.6 interface and interface relationship

  • Relationship between interfaces
  • Conflicts during interface inheritance
    • Conflict of public static constants
    • Conflict of public abstract methods
    • Conflict of public default methods
    • Conflict between public static methods and private methods
Relationship between interfaces
  • An interface can be "inherited" from another "interface" and can be "multi inherited".

    interface IA{}
    interface IB{}
    interface IC extends IA{}// Single inheritance
    interface ID extends IA,IB{} // Multiple inheritance
    interface IE extends ID{} // Multilayer inheritance
    
    public class Test {
        public static void main(String[] args) {
            /*
                Interface and relationship between interfaces: inheritance relationship
                    Single inheritance
                        public interface Interface name extends parent interface name {}
                    Multiple inheritance
                        public interface Interface name extends parent interface name 1, parent interface name 2 {}
                    Multilayer inheritance
                        public interface Parent interface name extends grandfather interface name {}
                        public interface Child interface name extends parent interface name {}
             */
        }
    }
    
    
Interface inheritance interface conflict
Conflict of public static constants
interface IA{
    public static final int a = 10;
    public static final int b = 30;
}
interface IB{
    public static final int a = 20;
}
interface IC extends IA,IB{//No inheritance a
}
//Test:
main(){
    System.out.println(IC.a);//FALSE
}
Public abstract method conflict
interface IA{
    public void show();
}
interface IB{
    public void show();
}
interface IC extends IA,IB{//IC inherits only one show()
}
class Zi implements IC{
    //Rewrite show() once
    public void show(){
    }
}
Conflict of public default methods
interface IA{
    public default void d1(){
    }
}
interface IB{
    public default void d1(){
    }
}
interface IC extends IA,IB{//You must rewrite d1() once
    public default  void d1(){
    }
}
Public static methods and private methods
  • No conflict, because static methods directly belong to the interface and can only be accessed directly using the interface, while private methods can only be accessed in the interface without conflict

Knowledge point – 3.7 conflict when implementing class inherits parent class and implements interface

  • Conflict of public static constants
  • Conflict of public abstract methods
  • Conflict of public default methods
  • Conflict of public static methods
  • Conflict of private methods
Conflict between public static constants of parent class and interface
class Fu{
    public static final int a = 10;
}
interface IA{
    public static final int a = 20;
}
class Zi extends Fu implements IA{//No inherited a variable
}
public class Demo {
    public static void main(String[] args) {
        System.out.println(Zi.a);//Compilation error
    }
}

Abstract method conflict between parent class and interface
abstract class Fu{
    public abstract void show();
}
interface IA{
    public void show();
}
class Zi extends Fu implements IA{// Must override
    
}
//Test:
main(){
    Zi z = new Zi();
    z.show();//a
}

Conflict between public default methods of parent class and interface
  • The default method that gives priority to access the parent class
class Fu{
    public void show(){
        System.out.println("a");
    }
}
interface IA{
    public default void show(){
        System.out.println("b");
    }
}
class Zi extends Fu implements IA{
}
//Test:
main(){
    Zi z = new Zi();
    z.show();//a
}

Public static methods of parent classes and interfaces
class Fu{
    public static void show(){
        System.out.println("fu...");
    }
}
interface IA{
    public static void show(){
        System.out.println("IA...");
    }
}
class Zi extends Fu implements IA{//Only the static methods of the "parent class" are inherited, and the static methods of the interface are not inherited

}
public class Demo {
    public static void main(String[] args) {
        Zi.show();//fu...
    }
}

Private methods of parent classes and interfaces
  • No conflict

Practice – 3.8 practice of abstract classes and interfaces

Requirements:

The usage of abstract classes and interfaces is analyzed and demonstrated through examples.

1. Examples:

Dog: as an abstract parent

Behavior: roar; Eat; --- > Abstract method

Anti drug dogs: inherited dogs

Behavior: roar; having dinner; Drug enforcement;

public abstract class Dog{
    public abstract void houJiao();
    public abstract void eat();
}

public interface JiDu{
    public abstract void jiDu();
}

public class JiDuDog extends Dog implements JiDu{
    // Rewrite the roar method
    // Rewrite the method of eating
    // Rewrite the anti drug method
}

  • If all subclasses of a method in a parent class have different implementations, the method should be defined as an abstract method, so the parent class is an abstract class (the parent class is generally an abstract class)
  • If a function is added by a class, the additional function can be defined in the interface and implemented by this class

analysis:

Because dogs are divided into many kinds, their ways of roaring and eating are different. They can't be specified in the description, that is, the behavior of roaring and eating can't be clear. When describing a behavior, the specific action of the behavior cannot be defined. In this case, the behavior can be written as an abstract behavior, and this class is also an abstract class.

However, some dogs have other additional functions, which are not in the system of this thing, such as anti drug dogs. There are many kinds of animals with the function of anti drug, such as anti drug pigs and anti drug mice. We can define this additional function in the interface, so that the anti drug dog can inherit the dog and realize the anti drug interface, so that the anti drug dog not only has the characteristics of the canine family, but also has the anti drug function.

  • Additional functions - > defined in the interface and implemented by the implementation class
  • Common functions - > defined in the parent class and inherited by the child class

realization:

//The phrase (anti narcotics) defining the anti drug interface is relatively long, so pinyin is used here instead
interface JiDu{
    //Anti drug
	public abstract void jiDu();
}
//Define canine family and store common functions
abstract class Dog{
    //having dinner
	public abstract void eat();
    //Roar
	public abstract void roar();
}
//Anti drug dogs belong to the canine family. Let them inherit the characteristics of the canine family,
//Since the anti drug dog has the anti drug function, it only needs to realize the anti drug interface, which ensures that the anti drug dog has the characteristics of canine and the anti drug function
class JiDuQuan extends Dog implements JiDu{
	public void jiDu() {
	}
	void eat() {
	}
	void roar() {
	}
}

//Anti drug pig
class JiDuZhu implements JiDu{
	public void jiDu() {
	}
}

Summary:

  • Additional functions - > defined in the interface and implemented by the implementation class
    • If you can determine the general function of the, use the default method
    • If the function cannot be determined, use abstract methods
  • Common functions - > defined in the parent class and inherited by the child class
    • If you can determine the general function of the, use the default method
    • If the function cannot be determined, use abstract methods

Chapter II polymorphism

Knowledge points - Overview

Polymorphism is the third feature of object-oriented after encapsulation and inheritance.

In life, such as running, kittens, dogs and elephants run differently. Another example is the action of flying. Insects, birds and planes fly differently. It can be seen that the same behavior can reflect different forms through different things. Polymorphism describes such a state.

definition

  • Polymorphism: refers to the same behavior with multiple different manifestations for different objects.
  • Polymorphism in program: it means that the same method has different implementations for different objects

Preconditions [ key ]

  1. Inherit or implement [one of two]
  2. The parent class reference points to the child class object [format representation]
  3. Rewriting of methods [meaning embodiment: no rewriting, meaningless]

Summary:

  • Polymorphism: refers to the same behavior with multiple different manifestations for different objects.
  • Conditions:
    • Inherit or implement
    • The parent class refers to an object that points to a child class
    • Method override

Knowledge points -- Realizing polymorphism

Embodiment of polymorphism: the reference of the parent class points to the object of its subclass:

Parent type variable name = new Subclass objects;
Variable name.Method name();

Parent class type: refers to the parent class type inherited by the child class object or the implemented parent interface type.

class Animal{}
class Cat extends Animal{}
class Dog extends Animal{}
clsss Person{}
//Test class:
main(){
    Animal a1 = new Cat();
    Animal a2 = new Dog();
    Animal a3 = new Person();//Compilation error, no inheritance relationship.
}

Summary:

  • The reference of the parent class points to the object of the child class

Knowledge points -- characteristics of accessing members in polymorphism

  • Access characteristics of member variables in polymorphism
    • Compile and run on the left
      • In short: in the case of polymorphism, the member variables of the parent class are accessed
  • Access characteristics of member methods in polymorphism
    • Non static method: compile to the left and run to the right
      • In short: when compiling, look for methods in the parent class, and when running, look for methods in the child class to execute
    • Static method: compile and run on the left
      • In short: when compiling, look for methods in the parent class, and when running, look for methods in the parent class to execute
  • Note: in the case of polymorphism, you cannot access the methods unique to subclasses
  • Demo code:
package com.lucky.demo10_Member access characteristics when polymorphic;

class Animal {
    int num = 10;

    public void eat() {
        System.out.println("Eat something...");
    }

    public static void sleep() {
        System.out.println("Animal sleep method...");
    }
}

class Dog extends Animal {
    int num = 20;

    @Override
    public void eat() {
        System.out.println("Eat bones...");
    }

    public static void sleep() {
        System.out.println("Dog sleep method...");
    }
    
    public void lookHome(){
        System.out.println("The dog is watching the house...");
    }
}

public class Test {
    public static void main(String[] args) {
        /*
            - Access characteristics of member variables in polymorphism: compile to find the parent class, and run to find the parent class
            - Access characteristics of member methods in polymorphism:
                Non static member method: compile to find the parent class and run to find the child class
                  Static member method: compile to find the parent class, and run to find the parent class

           Memory: only non static methods are compiling to find the parent class, running to find the child class, and the rest are to find the parent class
         */
        // The reference of the parent class points to the object of the child class
        Animal anl = new Dog();

        // Access member variables:
        System.out.println(anl.num);// 10

        // Access non static member methods:
        anl.eat();
        // Access static member methods:
        anl.sleep();
        
        // Access methods unique to subclasses
        // anl.lookHome();//  Compilation reports an error. Because polymorphic compilation looks at the parent class, there is no such method in the parent class, so compilation reports an error
    }
}

Knowledge points -- several forms of polymorphism

  • Polymorphism through inheritance:

    • Common parent polymorphism
    • Abstract parent polymorphism
  • Polymorphism through interface:

    • Parent interface polymorphism
  • Manifestations of polymorphism:

    • Common parent polymorphism

      public class Fu{}
      public class Zi extends Fu{}
      public class Demo{
          public static void main(String[] args){
              Fu f = new Zi();//On the left is a "parent class"
          }
      }
      
      
    • Abstract parent polymorphism

      public abstract class Fu{}
      public class Zi extends Fu{}
      public class Demo{
          public static void main(String[] args){
              Fu f = new Zi();//On the left is a "parent class"
          }
      }
      
      
    • Parent interface polymorphism

    public interface A{}
    public class AImp implements A{}
    public class Demo{
        public static void main(String[] args){
            A a = new AImp();
        }
    }
    

Knowledge points -- polymorphic application scenarios:

  • Variable polymorphism ----- > little significance
  • Formal parameter polymorphism ----- > common
  • Return value > common

Several application scenarios of polymorphism:

  • Variable polymorphism

    package com.lucky.demo12_Polymorphic application scenarios.demo1_Variable polymorphism;
    
     class Animal {
        public void eat(){
            System.out.println("Eat something...");
        }
    }
     class Cat extends Animal {
        @Override
        public void eat() {
            System.out.println("Cats eat fish...");
        }
    }
    
     class Dog extends Animal {
        @Override
        public void eat() {
            System.out.println("Dogs eat bones...");
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            // Variable polymorphism:
            Animal anl = new Dog();
            anl.eat();
        }
    }
    
    
  • Formal parameter polymorphism

    package com.lucky.demo12_Polymorphic application scenarios.demo2_Formal parameter polymorphism;
    
    class Animal {
        public void eat(){
            System.out.println("Eat something...");
        }
    }
    class Cat extends Animal {
        @Override
        public void eat() {
            System.out.println("Cats eat fish...");
        }
    }
    
    class Dog extends Animal {
        @Override
        public void eat() {
            System.out.println("Dogs eat bones...");
        }
    }
    public class Test {
        public static void main(String[] args) {
            // Call the invokeEat() method to pass in an object of type Animal
            Animal anl = new Animal();
            invokeEat(anl);
    
            System.out.println("==========================");
            // Call the invokeEat() method to pass in an object of Dog type
            Dog d = new Dog();
            invokeEat(d);
    
            System.out.println("==========================");
            // Call the invokeEat() method to pass in an object of Cat type
            Cat c = new Cat();
            invokeEat(c);
        }
    
        /**
         * Define a method whose parameters are of type Animal
         * @param anl
         */
        // Argument passed to formal parameter: Animal anl = anl;
        // Argument passed to formal parameter: Animal anl = d;
        // Argument passed to formal parameter: Animal anl = c;
        // Conclusion: if the type of the parameter is the parent type, the parameter can receive the object of the parent type and all its child objects
        public static void invokeEat(Animal anl){
            anl.eat();
        }
    
       /* public static void invokeEat(Cat cat){
            cat.eat();
        }
    
        public static void invokeEat(Dog dog){
            dog.eat();
        }*/
    }
    
    
  • Return value polymorphism

    package com.lucky.demo12_Polymorphic application scenarios.demo3_Return value polymorphism;
    
    class Animal {
        public void eat() {
            System.out.println("Eat something...");
        }
    }
    
    class Cat extends Animal {
        @Override
        public void eat() {
            System.out.println("Cats eat fish...");
        }
    }
    
    class Dog extends Animal {
        @Override
        public void eat() {
            System.out.println("Dogs eat bones...");
        }
    }
    
    public class Test {
        public static void main(String[] args) {
            // Call the getAnimal() method
            Animal anl = getAnimal("Animal");
            anl.eat();
    
            System.out.println("=======================");
            // Call the getAnimal() method
            Animal anl1 = getAnimal("Dog");
            anl1.eat();
    
            System.out.println("=======================");
            // Call the getAnimal() method
            Animal anl2 = getAnimal("Cat");
            anl2.eat();
        }
    
        // Conclusion: if the return value type of the method is the parent type, you can return the object of the parent type or all its subclass objects
        public static Animal getAnimal(String name) {
            if (name.equals("Animal")) {
                // Returns an object of the parent type
                Animal anl = new Animal();
                return anl;
    
            } else if (name.equals("Dog")) {
                // Returns an object of type Dog
                Dog d = new Dog();
                return d;
    
            } else {
                // Returns an object of type Cat
                Cat c = new Cat();
                return c;
            }
        }
    }
    
    
  • If the type of the parameter is the parent type, the parameter can receive the object of the parent type and all its subclass objects

  • If the type of the parameter is interface type, the parameter can receive all implementation class objects of the interface

  • If the return value type of a method is a parent type, you can return objects of the parent type or all its subclass objects

  • If the return value type of a method is an interface type, all implementation class objects of the interface can be returned

Knowledge points -- advantages and disadvantages of polymorphism

  • In the actual development process, the parent class type is used as the formal parameter of the method, passing the subclass object to the method and calling the method, which can better reflect the expansibility and convenience of polymorphism. But there are advantages and disadvantages

  • benefit

    • It improves the scalability of the code
  • malpractice

    • In the case of polymorphism, you can only call the common content of the parent class, not the unique content of the child class.
  • Sample code

class Animal {
    public void eat(){
        System.out.println("Eat something...");
    }
}
class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cats eat fish...");
    }

    public void catchMouse(){
        System.out.println("A cat catches a mouse...");
    }
}

class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println("Dogs eat bones...");
    }

    public void lookHome(){
        System.out.println("Dog watch...");
    }
}

public class Test {
    public static void main(String[] args) {
        /*
            Benefits and disadvantages of polymorphism:
                - benefit
                  - It improves the scalability of the code
                - malpractice
                  - In the case of polymorphism, you can only call the common content of the parent class, not the unique content of the child class.
         */
        Animal anl = new Cat();
        anl.eat();
        //anl.catchMouse();//  Compilation error

        System.out.println("======================");
        Animal anl2 = new Dog();
        anl2.eat();
        //anl2.lookHome();//  Compilation error

    }
}

Knowledge point -- reference type conversion

Upward transformation
  • The process of upward conversion from subclass type to parent type. This process is the default.

     Aniaml anl = new Cat();  
    
Downward transformation
  • The process of downconversion from parent type to child type is mandatory.

     Aniaml anl = new Cat();  
     Cat c = (Cat)anl;//Downward transformation
     c.catchMouse();// You can access the unique functions of subclasses to solve the disadvantages of polymorphism
    
    
instanceof keyword
  • There is a risk of forced downward conversion. It is best to make a verification before conversion:

  • Format:

    Variable name instanceof data type 
    If the object pointed to by the variable belongs to the data type, return true. 
    If the object pointed to by the variable does not belong to the data type, return false. 
    
    if( anl instanceof Cat){//Judge whether anl can be converted to Cat type. If yes, return: true; otherwise, return: false
        Cat c = (Cat)anl;//Secure conversion
    }
    

Chapter III internal classes

Knowledge point - internal class

What is an inner class

Define a Class A in another class B, which class A is called the inner class and B is called the outer class.

Member inner class

  • Member inner class: a class defined outside a method in a class.

Define format:

class External class {
    class Inner class{

    }
}

When describing things, if there are other things inside a thing, you can use the structure of inner class. For example, an automobile Car contains an Engine class. In this case, the Engine can be described by an internal class and defined in the member position.

Code example:

class Car { //External class
    class Engine { //Inner class

    }
}

Access characteristics

  • Internal classes can directly access members of external classes, including private members.
  • If an external class wants to access the members of an internal class, it must create an object of the internal class.

Create internal class object format:

External class name.Internal class name object name = new External type().new Internal type();

Access the demo with the following code:

package com.lucky.demo15_Member inner class;

public class Body {// External class

    int numW = 10;

    public void methodW(){
        System.out.println("Member methods of external classes methodW...");
        // To access internal class members:
        // Create an object of the member's internal class Heart
        //Body.Heart bh = new Body().new Heart();
        Heart bh = new Heart();

        // Access member variables and member methods of member internal classes
        System.out.println("Member variables of inner classes:"+bh.numN);
        bh.methodN();
    }

    public void showW(){
        System.out.println("Member methods of external classes showW...");
    }

    public class Heart{// Inner class

        int numN = 20;

        public void methodN(){
            System.out.println("Member methods of inner classes methodN...");
        }

        // A member of an inner class that accesses an outer class
        public void showN(){
            System.out.println("Member variables of external classes:"+numW);// 10
            showW();
        }

    }

}

package com.lucky.demo15_Member inner class;

public class Test {
    public static void main(String[] args) {
        /*
            Member inner class:
                Format:
                    public class External class{
                        public class Inner class{

                        }
                    }

                Create internal class object: external class name Internal class name object name = new external class name () New internal class name ();

                Access features:
                    1.Members of the external class can be accessed directly in the internal class
                    2.You must create an inner class object in an outer class to access members of an inner class
         */
        // Create an object of the member's internal class Heart
        Body.Heart bh = new Body().new Heart();

        // Access member variables and member methods of member internal classes
        System.out.println("Member variables of inner classes:"+bh.numN);
        bh.methodN();

        System.out.println("========================");

        // Create an external class object
        Body b = new Body();
        // Calling methods of external classes
        b.methodW();

        System.out.println("========================");
        // Calling the showN method using an internal class object
        bh.showN();

    }
}

Summary:

Inner class:Add a class A Defined in another class B Inside, inside A It's called an inner class, B Is called an external class.
Format of inner class of member:
    public class External class name{
         public class Internal class name{

        }
    }
Access characteristics of member internal classes:
    - Internal classes can directly access members of external classes, including private members.
    - If an external class wants to access the members of an internal class, it must create an object of the internal class.

How member inner classes are created:
    External class name.Internal class name object name = new External class name().new Internal class name();

Interview questions:

public class Body {

    int num = 10;

    public class Heart {
        int num = 20;

        public void methodN() {
            int num = 30;
            System.out.println("local variable num:" + num);// 30
            System.out.println("Member variables of inner class of member num:" + this.num);// 20
            System.out.println("Member variables of external classes num:" + Body.this.num);// 10
        }
    }
}

public class Test {
    public static void main(String[] args) {
        // Create an internal class object
        Body.Heart bh = new Body().new Heart();

        // Call methodN method
        bh.methodN();
    }
}

Knowledge point -- anonymous inner class

summary

  • Anonymous inner class: it is a simplified expression of inner class. Its essence is an anonymous subclass object with a concrete implementation parent class or parent interface.

Code one

abstract class Animal {
    public abstract void eat();
}

class Dog extends Animal {
    @Override
    public void eat() {
        System.out.println("Dogs eat bones...");
    }
}

public class Test {
    public static void main(String[] args) {
        /*
            Anonymous inner class:
                Essence: the essence of an anonymous inner class is an anonymous subclass object of a class
                Function: in fact, it has no function. It is used to simplify the code
                Format:
                    new Class name (){
                        Override abstract methods
                    };

                Usage scenario: if you want to get a subclass object of a class, you can directly create an anonymous inner class
         */
        // Requirement: execute the eat method of the Animal class
        /*
            analysis:
                1.Create a subclass to inherit the Animal class
                2.Override the abstract method eat in a subclass
                3.Create subclass objects
                4.Call eat method with subclass object
                The above four steps can't be less than one step. The first three steps are actually to get subclass objects of Animal class

           Thinking: can you omit the first three steps and directly get the subclass object of Animal class???
           Solution: use anonymous inner classes
         */
        // Create subclass objects
        Animal anl1 = new Dog();// Get the subclass object of the Animal class
        anl1.eat();

        System.out.println("==========================");
        // Create an anonymous inner class of Animal class (directly get the subclass object of Animal class)
        Animal anl2 = new Animal() {
            @Override
            public void eat() {
                System.out.println("Anonymous Inner Class ");
            }
        };
        anl2.eat();
        anl2.eat();
    }
}

Code two

interface IA{
    void method();
}
public class Test {
    public static void main(String[] args) {
        /*
            Anonymous inner class:
                Essence: the essence of an anonymous inner class is an anonymous implementation class object of an interface
                Function: in fact, it has no function. It is used to simplify the code
                Format:
                    new Interface name (){
                        Override abstract methods
                    };

                Usage scenario: if you want to get an interface implementation object, you can directly create an anonymous inner class
         */
        // Create the implementation class object of IA interface
        IA i = new IA() {
            @Override
            public void method() {
                System.out.println("Anonymous Inner Class ....");
            }
        };

        i.method();
    }
}

Chapter IV summary of the use of reference types

target

In actual development, the use of reference types is very important and common. We can further master the use of reference types on the basis of understanding the use of basic types. A basic type can be used as a member variable, as a parameter of a method, and as a return value of a method. Of course, a reference type can also be used. Here we use two examples.

route

  • Class name as method parameter and return value type
  • Abstract classes are used as method parameters and return value types
  • Interface as method parameter and return value type
  • Class as a member variable
  • Abstract classes are uncommon as member variables
  • Interfaces are uncommon as member variables

6.1 class name as method parameter and return value

public class Person {
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void show() {
        System.out.println(name + "," + age);
    }
}


public class Test {
    public static void main(String[] args) {
        /*
            Conclusion: the reference type is used as the parameter of the method, and the address value is passed
            Conclusion: the reference type is used as the return value of the method, and the return value is the address value
         */
        // Requirement 1: call method1 method
        // Create Person object
        Person p1 = new Person("Bingbing",18);// 0x11901
        method1(p1);
        p1.show();// Bingbing, 19

        System.out.println("==========================");
        // Requirement 2: call method2 method
        Person p2 = method2();// 0x11908
        p2.show();// Reba, 18

    }

    // Class as the parameter type of the method
    public static void method1(Person p){// 0x11901
       // Modify age
        p.age = 19;
    }

    // Class as the return value type of the method
    public static Person method2(){
        // Create Person object
        Person p = new Person("Reba",18);// 0x11908
        return p;
    }
}

6.2 abstract classes as method parameters and return values

  • Abstract class as formal parameter: it means that any "subclass object" of this abstract class can be accepted as an argument;
  • Abstract class as return value: indicates that "this method can return any subclass object of this abstract class";
/* Define an abstract class */
public abstract class Person{
    public void eat(){
        System.out.println("having dinner");
    }
    public abstract void work();
}
/*Define subclass Student*/
public class Student extends Person{
    public void work(){
        System.out.println("Students' job is to study...");
    }
}
/*Test class*/
public class Test{
     public static void main(String[] args) {
        //Call method
        //When an abstract class is used as a parameter, what is actually passed in is a subclass object of the abstract class
        method(new Student());
    }

    public static void method(Person p){
    }

    //Using abstract classes as method return value types
    public static Person method2(){
        
        //When an abstract class is used as a return value type, what is actually returned is a subclass object of the abstract class
        return new Student();
    }
    
}

6.3 interface as method parameter and return value

  • Interface as formal parameter of method: [same as abstract class]
  • Interface as return value of method: [same as abstract class]
public interface IA {
    void method();
}

public class Test {
    public static void main(String[] args) {
        // Requirement: call method1 method
        // Create an implementation class object of IA interface (anonymous inner class)
        IA i = new IA() {
            @Override
            public void method() {
                System.out.println("Anonymous inner class of interface 1...");
            }
        };

        method1(i);

        System.out.println("=====================");
        // Requirement: call method2 method
        IA i2 = method2();// 0x111
        i2.method();
    }

    // Interface as a formal parameter of a method: when calling, the passed in must be the implementation class object of the interface
    public static void method1(IA i){
        i.method();
    }

    // Interface as the return value type of method: when calling, the returned object must be the implementation class object of the interface
    public static IA method2(){
        IA i = new IA() {
            @Override
            public void method() {
                System.out.println("Anonymous inner class of interface 2...");
            }
        };// 0x111

        return i;// 0x111
    }
}

6.4 class name as member variable

Each of us (Person) has an ID card. In order to represent this relationship, we need to define a member variable of IDCard in Person. When defining the Person class, the code is as follows:

class Person {
    String name;//full name
    int age;//Age
}

Use String type for name and int type for age. In fact, String itself is a reference type. We often ignore that it is a reference type. If we continue to enrich the definition of this class, and add Person ID number, ID card issuing authority and other attributes, how will we write it? At this time, you need to write an IDCard class

Define IDCard (ID) class, add ID number, place of issue, and other attributes:

public class IDCard {
    String address;// address
    String number;// ID card No.

    public IDCard(String address, String number) {
        this.address = address;
        this.number = number;
    }
}

Modify the Person class:

public class Person {
    String name;// full name
    int age;// Age
    IDCard idCard;// ID
}

Test class:

public class Test {
    public static void main(String[] args) {
        // Create Person object
        Person p = new Person();
        // Assign values to the properties of the object
        p.name = "Bingbing";
        p.age = 18;

        // Create ID object
        IDCard idCard = new IDCard("Beijing","123");
        p.idCard = idCard;

        // Print p object attribute values
        System.out.println(p.name+","+p.age);// Bingbing, 18
        System.out.println("address:"+p.idCard.address);// Beijing
        System.out.println("ID card No.:"+p.idCard.number);// 123
    }
}

When a class is used as a member variable, the operation of assigning a value to it is actually an object assigned to it. Similarly, the interface is the same. For example, we use usb devices in our notebook case. Here, we only use small examples to familiarize you with the usage of reference types. This method will be used a lot in our employment class later.

6.5 abstract classes as member variables

  • An abstract class acts as a member variable -- when assigning a value to this member variable, it can be any subclass object of it
public class Person {
    String name;// full name
    int age;// Age
    // Abstract class as member variable
    Pet pet; // Pets
}


public abstract class Pet {// Pets
    public abstract void play();
}


class Dog extends Pet{
    @Override
    public void play() {
        System.out.println("The owner threw a UFO to amuse the dog...");
    }
}
public class Test {
    public static void main(String[] args) {
        // Create Person object
        Person p = new Person();

        // Assign a value to the property of the p object
        p.name = "Bingbing";
        p.age = 18;

        // Create pet object
        Dog dog = new Dog();
        p.pet = dog;// Subclass object assigned to abstract class

        // Print the value of the attribute
        System.out.println(p.name+","+p.age);// Bingbing, 18
        // Let pets play with their owners
        p.pet.play();
    }
}

6.6 interface as member variable

  • Interface type as member variable - same as abstract class
public interface Pet {// Pets
    public abstract void play();
}


public class Person {
    String name;// full name
    int age;// Age
    // Interface as a member variable
    Pet pet; // Pets
}


class Dog implements Pet{
    @Override
    public void play() {
        System.out.println("The master threw the dish to amuse the dog...");
    }
}
public class Test {
    public static void main(String[] args) {
        // Create Person object
        Person p = new Person();

        // Assign a pet to the p object
        Dog d = new Dog();
        p.pet = d;// Implementation class object assigned to interface


        // Pets using p
        p.pet.play();
    }
}

summary

- Be able to write out the definition format of the interface
    public interface Interface name{
			constant(jdk7 And before)
			Abstract method(jdk7 And before)
			Default method(jdk8)---default
			Static method(jdk8)
			Private method(jdk9)
	}

- Be able to write the implementation format of the interface
    public class Implementation class name implements Interface name 1,Interface name 2{}
	public class Implementation class name extends Parent class name implements Interface name 1,Interface name 2{}

- Be able to tell the characteristics of members in the interface
    Constants in interface: It is mainly for direct interface access
	Abstract methods in interfaces: It is mainly for implementation class rewriting
	Default method in interface: It is mainly used for implementation class rewriting or direct call
	Static methods in interfaces: Only for direct interface access
	Private method in interface: It can only be accessed directly inside the interface
            
- The premise of being able to say polymorphism
     1.Inherit or implement
	 2.The reference of the parent class points to the object of the child class
	 3.Method override
        
- Be able to write polymorphic formats
    The reference of the parent class points to the object of the child class\The reference of the interface points to the object that implements the class

- Be able to master the access characteristics of members in polymorphism:
	Member variable: Compile to see the parent class,Run to see the parent class(Look at the left,Run and look to the left)
	Non static member method: Compile to see the parent class,Run to see subclasses(Look at the left,Run and look to the right)
	Static member method:  Compile to see the parent class,Run to see the parent class(Look at the left,Run and look to the left)	

- Be able to understand polymorphic upward and downward transformation
    Upward transformation: It means that the subclass type is automatically converted to the parent type
            format: Parent type object name = Subclass object

    Downward transformation: It means that the parent class type is forced to convert to the child class type
             format: Subclass type object name = (Subclass type)Variable of parent type;
			be careful: The object pointed to by the parent type variable must be an object of the type to be converted,Otherwise, an exception will be reported

    instanceof keyword:  
			Variable name instanceof data type
            1.Judge whether the object pointed to by the variable belongs to the following data type,Return if it belongs to true
            2.Judge whether the object pointed to by the variable belongs to the following data type,If not, return false
                
- Be able to say the concept of internal class
   A class is defined in another class,The inner class is the inner class,The outer class is the outer class
                
- Be able to understand the writing format of anonymous internal classes
      new  Class name\Interface name(){
      	   Override abstract methods          
      };

Topics: Java