Understanding how drawLine works

喜欢而已 提交于 2019-12-23 08:33:07

问题


Given the following code:

import javax.swing.*;
import java.awt.*;

public class NewClass extends JPanel {
    public void paintComponent(Graphics g) {
        g.drawLine(0, 0, 90, 90);
    }

    public static void main(String[] args) {
        JFrame jf = new JFrame();
        jf.add(new NewClass());
        jf.setSize(500, 500);
        jf.setVisible(true);
    }
}

Why does it draw a line if the method drawLine is abstract and, as I managed to understand, an abstract method has no definition?

Thank you in advance!


回答1:


paintComponent() gets a non-abstract sub-class of Graphics, which implements drawLine(). It must get a non-abstract sub-class, since an abstract class cannot be instantiated.




回答2:


public void paintComponent(Graphics g) 

Here Graphics have abstract method drawLine that does not have a body implemented but its subclasses have concrete implementations for drawLine. When paintComponent is called, object of appropriate non-abstract subclass of Graphics is passed



来源:https://stackoverflow.com/questions/26235602/understanding-how-drawline-works

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!