To learn Java, you need to know these -- interface and polymorphism

Article catalog

Interface

  • The prototype of the method can be specified in the interface: method name, parameter list and return type,
    However, there is no method subject;
  • You can also include data members of basic data types, but they all default to static and
    final.

Function of interface

  • Inherit multiple designs.
  • Establish a "Protocol" between classes
    • The class is represented by an interface according to the functions it implements, without worrying about its class inheritance level; this can maximize the use of dynamic binding to hide implementation details.
    • Realize constant sharing among different classes.

Syntax of interface

  • The declaration format is
[interface modifier] interface interface name [extensions parent interface name]{
Prototype declaration or static constant for.. / / method
  • The data member of the interface must have an initial value, which can not be changed any more and can be omitted
    final keyword.

  • The method in the interface must be "abstract method", without method body, and can be omitted
    public and abstract keywords.

  • Declare an interface Shape2D, including π and a method prototype for calculating area

interface Shape2D{ //Declare Shape2D interface
	final double pi=3.14;//Data member - must initialize
	public abstract double area(); //Abstract method
}

In the declaration of the interface, some keywords are allowed to be omitted, and they can also be declared as follows

interface Shape2D{
	double pi=3.14;
	double area();
}

Implementation interface

  • The process of using an interface to design a class, called the implementation of an interface, uses implements
    Keyword, syntax is as follows:
public class class name implements interface name{
	//Method of implementing interface in class body
	//More variables and methods declared by this class
}
  • be careful:
    • All methods in the interface must be implemented;
    • Methods from interfaces must be declared public.

Circle implements Shape2D interface

public class Circle implements Shape2D {
    double radius;
    public Circle(double r) {
        radius=r;
    }
    
    public double area(){
            return (pi * radius * radius);
    }
     
}

Rectangle class implements Shape2D interface

class Rectangle implements Shape2D {
    
    int width,height;
    public Rectangle(int w,int h) {
        width=w;
        height=h;
    }
    
    public double area(){
        return (width * height);
    }
        
}

Interface test class

public class InterfaceTester {
    public static void main(String args[]){
    Rectangle rect=new Rectangle(5,6);
    System.out.println("Area of rect="+ rect.area());
    Circle cir=new Circle(2.0);
    System.out.println("Area ofcir= " + cir.area());
    }
}

Operation results

If two variables are declared as Shape2D when they are declared, they will be converted automatically when they are used.

public class InterfaceTester {
    public static void main(String args[]){
        Shape2D rect, cir;
        rect=new Rectangle(5,6);
        System.out.println("Area of rect="+ rect.area());
        cir=new Circle(2.0);
        System.out.println("Area ofcir= " + cir.area());
    }
}

Operation result:

Syntax for implementing multiple interfaces

  • A class can implement multiple interfaces, through which multiple inheritance of design can be realized.
  • The syntax for implementing multiple interfaces is as follows
[class modifier] class name implements interface 1, interface 2{

}
  • Declare the Circle class to implement the interfaces Shape2D and Color
    • Shape2D has constant pi and area() methods to calculate the area;
    • Color has setColor method, which can be used to assign colors;
    • By implementing these two interfaces, the Circle class can have the members of these two interfaces at the same time, achieving the purpose of multiple inheritance of the design.
interface Shape2D{ //Declare Shape2D interface
    final double pi=3.14;
    //Data members must be initialized
    public abstract double area(); //Abstract method
}
interface Color{
    void setColor(String str); //Abstract method
}

Implement multiple interfaces

public class Circle implements Shape2D,Color {
    double radius;
    String color;
    public Circle(double r) {
        radius=r;
    }
    
    public double area(){
            return (pi * radius * radius);
    }
    public void setColor(String str){//Define how setColor() is handled
        color=str;
        System.out.println("color=" +color);
    }
}

Test class:

public class InterfaceTester {
    public static void main(String args[]){
        Circle cir;
        cir=new Circle(2.0);
        cir.setColor("blue");
        System.out.println("Area of cir= " + cir.area());
    }
}

Operation result:

Interface extension

  • A class that implements an interface must also implement its super interface.
  • Syntax for interface extensions
Name of interface sub interface name of extensions super interface 1, super interface name 2{

}

Type conversion

The concept of type conversion

  • Also known as type casting.
  • Conversion mode
    • Implicit type conversion;
    • Explicit type conversion.
  • change direction
    • Upward transformation;
    • Downward transformation,

Type conversion rules

  • Conversion between basic types
    • Converts a value from one type to another.
  • Type conversion of reference variable
    • Converting a reference to another type of reference does not change the type of the object itself.
    • Can only be converted to
      • The type of any (direct or indirect) superclass (upward transformation);
      • An interface (upward transformation) implemented by the class to which the object belongs (or its superclass);
      • The type of object to which the reference refers (the only case where the transition can be down).
  • When a reference is converted to its superclass reference, only the sound in the superclass can be accessed through it
    The method is clear.

Implicit type conversion

  • Basic data type
    Among the types that can be converted, the one with low storage capacity will automatically convert to the one with high storage capacity.
  • Reference variable
    Is converted to a more general class, for example:
Employee emp;
emp = new Manager(); //Assign Manager type objects directly to
//Reference variable of Employee class, the system will
//Automatically mold the Manage object into the Employee class
  • The interface type implemented by the class to which the object belongs, for example:
Car jetta = new Car();
Insurable item = jetta;

Explicit type conversion

  • Basic data type
(int)871.34354;// The result is 871
(char)65;//Result is' A '
(long)453;//453L
  • Reference variable
Employee emp;
Manager man;
emp = new Manager();
man = (Manager)emp; //Explicitly convert emp to the type of object it points to

Main applications of type conversion

  • Assignment conversion
  • Method call transformation
  • Arithmetic expression conversion
  • String conversion

Main applications of type conversion

  • Assignment conversion
    The expression or object type to the right of the assignment operator is converted to the type to the left;
  • Method call transformation
    The type of the argument is converted to the type of the parameter;
  • Arithmetic expression conversion
    In the mixed arithmetic operation, the operands of different types are converted to the same type for further operation;
  • String conversion
    When a string connection operation is performed, if one operand is a string and the other operand is of a different type, the other type is automatically converted to a string.

polymorphic

The concept of polymorphism

  • Superclass objects and objects of multiple subclasses derived from the same superclass can be treated as objects of the same type;
  • Objects of different types that implement the same interface can be treated as objects of the same type;
  • You can send the same message to these different types of objects, because of polymorphism, these different classes
    Objects can behave differently when they respond to the same message.
  • for example
    • All objects of the Object class respond to the toString() method
    • All objects of the BankAccount class respond to the deposit() method

Purpose of polymorphism

  • Make the code simple and easy to understand;
  • So that the program has good scalability.

Posted on Sun, 10 May 2020 21:04:56 -0700 by mits