自己比较懒,上次面试遇到这个问题,回来查了下。网上查了,大概有这两种例子。
1.一种是普通的超类,子类覆盖父类的方法。
2.父类是抽象类,子类实现父类的抽象方法。
1.网上摘抄:
Game类是Football、Basketball、Popolong的父类,Games类使用前面4个类。
Java根据动态绑定决定执行“更具体”的方法,即子类方法。
- //Game.java
- package cn.edu.uibe.oop;
- public class Game {
- protected void play(){
- System.out.println( "play game" );
- }
- }
- //Football.java
- package cn.edu.uibe.oop;
- public class Football extends Game {
- protected void play() {
- System.out.println( "play football" );
- super .play();
- }
- void f(){
- play();
- }
- }
- //Basketball.java
- package cn.edu.uibe.oop;
- public class Basketball extends Game{
- protected void play() {
- System.out.println( "play basketball" );
- }
- }
- //Popolong.java
- package cn.edu.uibe.oop;
- public class Popolong extends Game {
- protected void play() {
- System.out.println( "play popolong" );
- }
- }
- //Games.java
- package cn.edu.uibe.oop;
- public class Games {
- public static void main(String[] args) {
- Game[] games = new Game[ 10 ];
- games[ 0 ] = new Basketball();
- games[ 1 ] = new Football();
- games[ 2 ] = new Popolong();
- for ( int i= 0 ;i<games.length;i++){
- if (games[i]!= null )
- games[i].play();
- }
- }
- }
2.from network
如在计算公司雇员工资的超类中
// 用抽象方法作为多态接口
public abstract class Employee {
...
public abstract double earnings(); //定义抽象方法作为多态接口
}
//这个方法将作为多态接口被子类的方法所覆盖
public class Manager extends Employee {
...
public double eamings () return 0.0;
抽象方法也可用protected.
- public class CircleShapeApp{
- public static void main(String[] args) {
- Circle circle = new Circle( 12.98 );
- Sphere sphere = new Sphere( 25.55 );
- Shape shape = circle; //向上转型
- //多态调用
- shape.computeArea();
- shape.computeVolume();
- System.out.println( "circle area: " + shape.getArea());
- System.out.println( "circle volume: " + shape.getVolume());
- //多态调用
- shape = sphere;
- shape.computeArea();
- shape.computeVolume();
- System.out.println( "Sphere area: " + shape.getArea());
- System.out.println( "Sphere volume: " + shape.getVolume());
- }
- }