为什么我不需要创建对象?

时间:2014-04-23 13:26:05

标签: java swing object joptionpane

import javax.swing.JoptionPane;

class Hat
{
  public static void main(String[]args)
   {

      String fn = JOptionPane.showInputDialog("Enter first number");
      String sn = JOptionPane.showInputDialog("Enter second number");

      int num1 = Integer.parseInt(fn);

      int num2 = Integer.parseInt(sn);

      int sum = num1 + num2;

      JOptionPane.showMessageDialog(null,"The answer is " +sum,"the title");
   }
}

为什么没有必要创建一个对象来使用JOptionPane类中的showInputDialog方法? 为什么在showMessageDialog方法中使用null?

3 个答案:

答案 0 :(得分:2)

showMessageDialog方法是static,因此不存在于实例上的类中。 Here is a little more explanation about static methods

第一个参数是父类,它指定相对于OptionPane属于哪个其他Frame的父类。如果是null,则OptionPane独立于任何其他帧。 See the documentation

> parentComponent - determines the Frame in which the dialog is
> displayed; if null, or if the parentComponent has no Frame, a default
> Frame is used

答案 1 :(得分:0)

因为showInputdialog是静态方法。它不是逻辑上附加到对象。它更像是一个由类本身暴露的功能。

答案 2 :(得分:-1)

该方法中使用的所有方法/变量都是方法范围或静态方法。 JOptionPane.showMessageDialog()例如是静态的,而num1 / num2都是方法范围。