小白教程

 找回密码
 立即注册
小白教程 首页 系列教程 Java系列教程 查看内容

Java 抽象类

发布者: 小白教程



继承抽象类

我们能通过一般的方法继承Employee类:

  1. /* 文件名 : Salary.java */
  2. public class Salary extends Employee
  3. {
  4. private double salary; //Annual salary
  5. public Salary(String name, String address, int number, double
  6. salary)
  7. {
  8. super(name, address, number);
  9. setSalary(salary);
  10. }
  11. public void mailCheck()
  12. {
  13. System.out.println("Within mailCheck of Salary class ");
  14. System.out.println("Mailing check to " + getName()
  15. + " with salary " + salary);
  16. }
  17. public double getSalary()
  18. {
  19. return salary;
  20. }
  21. public void setSalary(double newSalary)
  22. {
  23. if(newSalary >= 0.0)
  24. {
  25. salary = newSalary;
  26. }
  27. }
  28. public double computePay()
  29. {
  30. System.out.println("Computing salary pay for " + getName());
  31. return salary/52;
  32. }
  33. }

尽管我们不能实例化一个Employee类的对象,但是如果我们实例化一个Salary类对象,该对象将从Employee类继承3个成员变量和7个成员方法。

  1. /* 文件名 : AbstractDemo.java */
  2. public class AbstractDemo
  3. {
  4. public static void main(String [] args)
  5. {
  6. Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
  7. Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
  8. System.out.println("Call mailCheck using Salary reference --");
  9. s.mailCheck();
  10. System.out.println("\n Call mailCheck using Employee reference--");
  11. e.mailCheck();
  12. }
  13. }

以上程序编译运行结果如下:

  1. Constructing an Employee
  2. Constructing an Employee
  3. Call mailCheck using Salary reference --
  4. Within mailCheck of Salary class
  5. Mailing check to Mohd Mohtashim with salary 3600.0
  6. Call mailCheck using Employee reference--
  7. Within mailCheck of Salary class
  8. Mailing check to John Adams with salary 2400.


上一篇:Java 多态下一篇:Java 封装

Archiver|手机版|小黑屋|小白教程 ( 粤ICP备20019910号 )

GMT+8, 2024-11-24 13:26 , Processed in 0.014062 second(s), 18 queries .

Powered by Discuz! X3.4

© 2001-2017 Comsenz Inc. Template By 【未来科技】【 www.wekei.cn 】

返回顶部