Java abstract 关键字
实例
abstract 抽象方法属于抽象类,它没有主体。主体由子类提供:
// abstract classabstract class Main {public String fname = "John";public int age = 24;public abstract void study(); // abstract method}// Subclass (inherit from Main)class Student extends Main {public int graduationYear = 2018;public void study() { // the body of the abstract method is provided hereSystem.out.println("Studying all day long");}}// Code from filename: Second.javaclass Second {public static void main(String[] args) {// create an object of the Student class (which inherits attributes and methods from Main)Student myObj = new Student();System.out.println("Name: " + myObj.fname);System.out.println("Age: " + myObj.age);System.out.println("Graduation Year: " + myObj.graduationYear);myObj.study(); // call abstract method}}
定义与用法
abstract 关键字是非访问修饰符,用于类和方法。
类:抽象类是一个受限类,不能用于创建对象(要访问它,必须从另一个类继承)。
方法:抽象方法只能在抽象类中使用,并且没有主体。主体由子类(继承自)提供。
关联页面
可以访问本站的 Java 修饰符 学习更多相关知识。