开发者

Calling a method in java

public class DialogBox {
    public static void main (String arg[]) {
        String inputCourseCode;
        inputCourseCode = this.inputCourseCode();
    }
    public String inputCourseCode() {
        String input = JOptionPane.showInp开发者_如何转开发utDialog("Input the course code of this course:");
        return input;
    }
}

How to call the method inputCourseCode in main function?


You need to have an instance of DialogBox in order to call the inputCourseCode method.

For example:

public static void main (String arg[]) 
{
    String inputCourseCode;
    DialogBox box = new DialogBox();
    inputCourseCode = box.inputCourseCode();
}

main is a static method; consequently, it does not have access to a 'this' reference.


It's an instance method, so you need an instance of DialogBox to call the method.

public static void main (String arg[]) {
    DialogBox foo = new DialogBox();
    String inputCourseCode = foo.inputCourseCode();
}


It needs to be static

public static String inputCourseCode()

then within Main you remove the this.


 public static void main (String arg[]) {
        String inputCourseCode;

        DialogBox d = new DialogBox();  //create instance 
        d.inputCourseCode();  //call method
    }

inputCourseCode is a method of DialogBox class, you need a reference to an instance of that class to call it. If you need to call that function without an istance class you need to declare it as static:

 public static String inputCourseCode() {
        String input = JOptionPane.showInputDialog("Input the course code of this course:");
        return input;
    }

Then you can call it from main without create an object:

public static void main (String arg[]) {
            String inputCourseCode;

            DialogBox.inputCourseCode();  //call  static method
}


new DialogBox().inputCourseCode();

You need to instantiate your class to access non-static members.

See Java Tutorial: Understanding Instance and Class Members


Well it depends on your need.

  1. If you want it to be tied at class level, then just make it static and remove 'this' from this.inputCourseCode() in the current code and it will work.

  2. If you want it to be part of each object then you need to create object of DialogBox and call it explicitly as follows : DialogBox dialogBox = new DialogBox(); dialogBox.inputCourseCode();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜