为什么下面的代码能够在不实现的情况下调用抽象方法?

时间:2019-06-22 18:07:42

标签: java abstract

该程序旨在创建一个GUI组件,该组件显示总空间量,可用空间和总可用空间的百分比:

package com.java24hours;

import java.io.IOException;
import java.nio.file.*;
import javax.swing.*;

public class FreeSpacePanel extends JPanel {
    JLabel spaceLabel = new JLabel("Disk space: ");
    JLabel space = new JLabel();

    public FreeSpacePanel() {
        super();
        add(spaceLabel);
        add(space);
        try {
            setValue();
        } catch (IOException ioe) {
            space.setText("Error");
        }
    }

    private final void setValue() throws IOException {
        // get the current file storage pool
        Path current = Paths.get("");
        FileStore store = Files.getFileStore(current);
        // find the free storage space
        long totalSpace = store.getTotalSpace();
        long freeSpace = store.getUsableSpace();
        // get this as a percentage (with two digits)
        double percent = (double)freeSpace / (double)totalSpace * 100;
        percent = (int)(percent * 100) / (double)100;
        // set the label's text
        space.setText(freeSpace + " free out of " + totalSpace + " ("
            + percent + "%)");
    }
}

您可以看到创建了一个名为“ store”的FileStore对象,然后在以下几行中直接调用FileStore方法getTotalSpace()getUseableSpace(),而无需执行。但是,FileStore类将这些方法声明为抽象的,那怎么可能呢?

1 个答案:

答案 0 :(得分:3)

Files.getFileStore返回实现所需方法的FileStore的一些非抽象子类的实例。

要查看它是什么类,请执行以下操作:

System.out.println(store.getClass());

在Linux系统上,我看到该对象是类sun.nio.fs.LinuxFileStore的实例。