import java.util.Scanner;
class A{
int ivar = 7;
void m1(){
System.out.print("A's m1, ");
}
void m2(){
System.out.print("A's m2, ");
}
void m3(){
System.out.print("A's m3, ");
}
}
class B extends A{
void m1(){
System.out.print("B's m1, ");
}
}
class C extends B{
void m3(){
System.out.print("C's m3, "+(ivar + 6));
}
}
public class Main{
public static void main(String args[]){
A a = new A();
B b = new B();
C c = new C();
A a2 = new C();
a.m1();
b.m1();
c.m3();
}
}
运行结果:
A's m1, B's m1, C's m3, 13
//下面是一个很好的多态的例子
package com.company; public class Main { public static void main(String[] args) { Animal dog = new Dog("旺财"); Animal cat = new Cat("招财猫"); dog.eat(); cat.eat(); } } class Animal { private String name; public Animal(String name){ this.name = name; } public void eat(){ } } class Dog extends Animal { public Dog(String name) { super(name); } public void eat(){ System.out.println("吃骨头"); } } class Cat extends Animal { public Cat(String name){ super(name); } public void eat(){ System.out.println("吃鱼肉"); } }
运行结果:
吃骨头
吃鱼肉