Polymorphic: Improves code extensibility, maintainability, the same reference type, and different operations with different instances.
Two implementations: ① the parent class as a method parameter to implement polymorphism ② using the parent class as the method return value.
Implementing polymorphic Two features ① subclasses overriding a parent class ② a parent class reference to a
Parent f=new Child ();
Properties See left
method, compile to see left run see right
For subclass-specific methods, down
Sub-z= (child) F;
Polymorphic use: ① Create a parent class variable, instantiate a subclass object
② the parent type as a parameter type, and the subclass and subclass object are passed in as parameters
③ using the parent class as the return value of the method
/*1, using polymorphic implementation of the subtraction calculator,
* Calculation of different subclasses based on operator different instantiation (operator can receive input by keyboard)
For example: addition has num1, num2 attribute, method: Calculate sum
Subtraction has NUM1, num2 properties, Method: Calculate the difference */
public class Test05 {
public static void Main (string[] args) {
System.out.println ("Please enter an operator");
Scanner input = new Scanner (system.in);
String oparator = Input.next ();
while (!oparator.equals ("+") &&!oparator.equals ("-") &&!oparator.equals ("*") &&! Oparator.equals ("/")) {
SYSTEM.OUT.PRINTLN ("You entered the operator incorrectly, please re-enter");
Oparator = Input.next ();
}
Double result = 0.0;
Operation op = null;
Switch (oparator) {
Case "+":
op = new Add (4, 2);
Break
Case "-":
op = new Subtract (4, 2);
Break
Case "*":
op = new Mul (4, 2);
Break
Case "/":
op = new Div (4, 2);
Break
}
result = calculation.cal (OP);
SYSTEM.OUT.PRINTLN (result);
}
}
Class Calculation {
public static double Cal (Operation op) {
return Op.calculate ();
}
}
Class Operation {
Double NUM1;
Double num2;
Public operation () {
}
Public operation (double NUM1, double num2) {
Super ();
THIS.NUM1 = NUM1;
this.num2 = num2;
}
Public double Calculate () {
return 0.0;
}
}
Class Add extends Operation {
Public Add (double NUM1, double num2) {
Super (NUM1, num2);
}
@Override
Public double Calculate () {
TODO auto-generated Method Stub
return NUM1 + num2;
}
}
Class Subtract extends Operation {
Public Subtract (double NUM1, double num2) {
Super (NUM1, num2);
}
@Override
Public double Calculate () {
return num1-num2;
}
}
Class Mul extends Operation {
Public Mul (double NUM1, double num2) {
Super (NUM1, num2);
}
@Override
Public double Calculate () {
return NUM1 * NUM2;
}
}
Class Div extends Operation {
Public Div (double NUM1, double num2) {
Super (NUM1, num2);
}
@Override
Public double Calculate () {
return num1/num2;
}
}
Java Object-oriented (polymorphic)