Java 多态的例子
2017-06-12 本文已影响24人
奔跑的笨鸟
多态就是通过继承和动态绑定来决定程序使用哪个实现.
一个简单的例子。
interface Animal {
public void eat();
}
class Whale extends SeaAnimal {
int age = 20;
@Override
public void eat() {
System.out.println("Whale is eatting a small fish");
}
private void swimming() {
System.out.println("Whale is swimming");
}
@Override
public int getAge() {
return age;
}
public static void staticSwimming() {
System.out.println("Static whale is swimming .");
}
}
public class SeaAnimal implements Animal {
int age = 10;
private void swimming() {
System.out.println("SeaAnimal is swimming.");
}
public static void staticSwimming() {
System.out.println("Static seaAnimal is swimming.");
}
public int getAge() {
return age;
}
public static void main(String[] args) {
SeaAnimal animal = new Whale();
animal.swimming();
animal.eat();
animal.staticSwimming();
System.out.println("The age is " + animal.age);
System.out.println("The age is " + animal.getAge());
}
@Override
public void eat() {
System.out.println("SeaAnimal is eatting a small fish");
}
}
输出结果:
SeaAnimal is swimming.
Whale is eatting a small fish
Static seaAnimal is swimming.
The age is 10
The age is 20
从例子可以看出:
- 成员变量不具备多态
-
private
方法不具备多态 -
static
方法不具备多态 - 构造方法不具备多态