java中多态的案例_Java 多态的例子

多态就是通过继承和动态绑定来决定程序使用哪个实现.

一个简单的例子。

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方法不具备多态

构造方法不具备多态

你可能感兴趣的:(java中多态的案例)