java技术博客

jsp博客
数据加载中……
java的动态多态
/**
 * 通过本程序的测试,主要学习抽象类及子类,抽象方法的实现
 * 动态绑定,多态
 
*/

 
import java.text.NumberFormat;

public class AbstractTest
{
    
public static void main(String[] args)
    
{
        Person[] p 
= new Person[2];
        p[
0= new Worker("Jack"1000);
        p[
1= new Student("Tom""Computer");
        
        
for(int i = 0; i < p.length; i++)
        
{
            Person people 
= p[i];
            System.out.println(people.getDescription());
        }

    }

}


/**
 * 抽象类
 
*/

abstract class Person
{
    
private String strName;

    
public Person(String strName)
    
{
        
this.strName = strName;
    }


    
public String getName()
    
{
        
return strName;
    }


    
//抽象方法,返回人的描述
    public abstract String getDescription();
}


/**
 * 工人类,扩展了抽象类,并实现了抽象方法
 
*/

class Worker extends Person
{
    
private double salary;
    
    
public Worker(String strName, double s)
    
{
        
super(strName);
        salary 
= s;
    }

    
    
public String getDescription()
    
{
        NumberFormat formate 
= NumberFormat.getCurrencyInstance();
        
return "the worker with a salary of " + formate.format(salary);
    }

}


/**
 * 学生类,扩展了抽象类,实现了抽象方法
 
*/

class Student extends Person
{
    
private String strMajor;
    
    
public Student(String strName, String strMajor)
    
{
        
super(strName);
        
this.strMajor = strMajor;
    }

    
    
public String getDescription()
    
{
        
return "the student majoring in " + strMajor;
    }

}

posted on 2008-11-07 16:31 郭兴华 阅读(268) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: