Java abstract 关键字

实例

abstract 抽象方法属于抽象类,它没有主体。主体由子类提供:

  1. // abstract class
  2. abstract class Main {
  3. public String fname = "John";
  4. public int age = 24;
  5. public abstract void study(); // abstract method
  6. }
  7. // Subclass (inherit from Main)
  8. class Student extends Main {
  9. public int graduationYear = 2018;
  10. public void study() { // the body of the abstract method is provided here
  11. System.out.println("Studying all day long");
  12. }
  13. }
  14. // Code from filename: Second.java
  15. class Second {
  16. public static void main(String[] args) {
  17. // create an object of the Student class (which inherits attributes and methods from Main)
  18. Student myObj = new Student();
  19. System.out.println("Name: " + myObj.fname);
  20. System.out.println("Age: " + myObj.age);
  21. System.out.println("Graduation Year: " + myObj.graduationYear);
  22. myObj.study(); // call abstract method
  23. }
  24. }

定义与用法

abstract 关键字是非访问修饰符,用于类和方法。

类:抽象类是一个受限类,不能用于创建对象(要访问它,必须从另一个类继承)。

方法:抽象方法只能在抽象类中使用,并且没有主体。主体由子类(继承自)提供。


关联页面

可以访问本站的 Java 修饰符 学习更多相关知识。

分类导航