多态指的是一个对象具备多种形态(父类的引用类型变量指向了子类的对象)。在使用需注意如下几点:
一、使用前提:必须存在继承或者实现关系。
二、使用细节
存在2个类:Animal和Mouse,其中Mouse继承了Animal类。
Animal:
public abstract class Animal {
String name;
//成员变量
String color = "动物色";
//构造方法
public Animal(String name){
this.name = name;
}
//成员方法
public abstract void run();
//静态成员方法
public static void eat() {
System.out.println("动物在吃..");
}
}
Mouse:
public class Mouse extends Animal{
//成员变量
String color = "黑色";
public Mouse(String name) {
super(name);
}
//成员方法
public void run() {
System.out.println(name + "四条腿慢慢的走!");
}
//静态成员方法
public static void eat() {
System.out.println("老鼠在偷吃..");
}
//特有方法
public void dig() {
System.out.println("老鼠在打洞..");
}
}
1. 多态情况下,子父类存在同名的成员变量时,访问的是父类的成员变量。
2. 多态情况下,子父类存在同名的非静态的成员函数时,访问的是子类的成员函数。
3. 多态情况下,子父类存在同名的静态的成员函数时,访问的是父类的成员函数。
4. 多态情况下,不能访问子类特有的成员(编译看左边,运行不一定看右边)。
三、运用场景
有三个类:Shape、Circle、Rect,其中Circle、Rect继承了Shape类。
Shape:
abstract class Shape{
//求图形面积
public abstract void getArea();
//求图形周长
public abstract void getLength();
}
Circle:
public class Circle extends Shape {
public static final double PI = 3.14;
double r;
public Circle(double r) {
this.r = r;
}
public void getArea() {
System.out.println("圆形的面积:" + PI * r * r);
}
public void getLength() {
System.out.println("圆形的周长:" + 2 * PI * r);
}
}
Rect:
public class Rect extends Shape {
int width;
int height;
public Rect(int width, int height) {
this.width = width;
this.height = height;
}
public void getArea() {
System.out.println("矩形的面积:" + width * height);
}
public void getLength() {
System.out.println("矩形的周长:" + 2 * (width + height));
}
}
1. 用于形参类型的时候,可以接收更多类型的数据 。
2. 用于返回值类型的时候,可以返回更多类型的数据。