多态性(Polymorphism)
Polymorphism
Polymorphism: Means many (poly) shapes (morph)
In OO programming, it means the ability of an object to take on many forms
It is an important feature of OO language
The most common use of polymorphism in Java:
Overloading: two or more methods with different signatures
Overriding: replacing an inherited method with another having the same signature
When a parent class reference is used to refer to a child class object.
Methods Overloading:
What is method overloading?
Multiple definitions for a method with the same name and return type, but different arguments
If the number of arguments is the same, at least one argument must have a different type.
1 class Maximum { 2 int max (int x, int y) { 3 if (y <= x){ 4 return x;} 5 else{ 6 return y; 7 } 8 } 9 10 int max (int x, int y, int z) { 11 if (y <= x && z <= x){ 12 return x;} 13 else { 14 if(y <= z){ 15 return z;} 16 else {return y; 17 } 18 } 19 } 20 }
1 class maxTest { 2 public static void main(String[] args){ 3 int a = 23; int b= 12; int c = 14; 4 int d = 13; int e=3; 5 6 Maximum myMax = new Maximum(); 7 System.out.println("max(" + a + "," + b +") = " 8 + myMax.max(a,b) ); 9 System.out.println("max(" + c + "," + 10 d +","+e +")= "+ myMax.max(c,d,e) ); 11 } 12 }
The purpose of overloading:
So you can use the same names for methods that do essentially the same thing Example: println(int), println(double), println(boolean), println(String), etc.
So you can supply defaults for the parameters:
int increment(int amount) {
count = count + amount;
return count;
}
int increment() {
return increment(1);
}
Notice that one method can call another of the same name So you can supply additional information:
void printResults() {
System.out.println("total = " + total + ", average = " + average);
}
void printResult(String message) {
System.out.println(message + ": ");
printResults();
}
DRY (Don’t Repeat Yourself)
When you overload a method with another, very similar method, only one of them should do most of the work:
void debug() {
System.out.println("first = " + first + ", last = " + last);
for (int i = first; i <= last; i++) {
System.out.print(dictionary[i] + " ");
}
System.out.println();
}
void debug(String s) {
System.out.println("At checkpoint " + s + ":");
debug();
}
Multiple Constructors
Constructor :
Has the same name as the name of the class
Does NOT include a return type, since constructors never return a value
If you don't write any constructor, the compiler will (in effect) write one for you: ClassName() {}: no arguments and performs no action
1 public class MyAnswers { 2 String myAnswer=“don’t know”; 3 4 public MyAnswers(String answer) { 5 this.myAnswer=answer; 6 //This code will not initialise myAnswer in an object.Do not introduce local variables with the same name as the instance fields 7 } 8 9 public void MyAnswer() { 10 System.out.println("Hi, "+myAnswer); 11 } 12 13 public static void main (String[] args){ 14 MyAnswers answerObj1=new MyAnswers(“One"); 15 answerObj1.sayMyAnswer(); 16 } 17 } 18
Multiple constructors:
Have the same name with different signatures Which constructor is called depends on the signature
public static void main (String[] args){
MyAnswers answerObj1=new MyAnswers(“One");
answerObj1.sayMyAnswer();
MyAnswers answerObj2=new MyAnswers();
answerObj2.sayMyAnswer();
MyAnswers answerObj3=new MyAnswers(1);
answerObj3.sayMyAnswer();
Method Overriding:
Subclass to provide a specific implementation of a method that is already provided by its superclasses
To override a method:
The method has the same name with the method of the superclass Same arguments as well
public class SuperClass {
public int methodA (int i, String s) {
bodyA
}
}
public class SubClass extends SuperClass {
public int methodA (int i, String s) {
bodyB
}
}
If we call methodA from an instance of SuperClass bodyA runs;
if we call methodA from an instance of SubClass bodyB runs
In SubClass, we can access bodyA with:
super.methodA(int i, String s)
Static methods cannot be overwritten
public class TextPrint {
public String words;
public TextPrint(String w){
this.words=w;
}
public void printText(){
System.out.println("Superclass method, "+this.words);
}
}
public class TextPrintSub extends TextPrint{
public TextPrintSub(String s){
super(s);
}
public void printText(){
super.printText();
System.out.println("Subclass method, "+this.words);
}
}
You can create a collection of objects with different behaviours.
public abstract class Animal {
public String species;
public abstract void eat();
}
public class Horse extends Animal{
public Horse(){
this.species="Horse";
}
public void eat(){
System.out.println(" eat grass...");
}
}
public class Tiger extends Animal{
public Tiger(){
this.species="Tiger";
}
public void eat(){
System.out.println(" eat meat...");
}
}
public class ZooDemo {
public static void main(String[] args){
Animal[] zoo=new Animal[2];
zoo[0]=new Horse();
zoo[1]=new Tiger();
for(Animal z: zoo)
z.eat();
}
}