hkguile
hkguile

Reputation: 4359

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.showInputDialog("Input the course code of this course:");
        return input;
    }
}

How to call the method inputCourseCode in main function?

Upvotes: 1

Views: 355

Answers (6)

Rishikesh Dhokare
Rishikesh Dhokare

Reputation: 3589

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();

Upvotes: 0

Heisenbug
Heisenbug

Reputation: 39164

 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
}

Upvotes: 1

Carlos Quintanilla
Carlos Quintanilla

Reputation: 13303

It needs to be static

public static String inputCourseCode()

then within Main you remove the this.

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359826

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();
}

Upvotes: 1

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

new DialogBox().inputCourseCode();

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

See Java Tutorial: Understanding Instance and Class Members

Upvotes: 0

Brandon E Taylor
Brandon E Taylor

Reputation: 25349

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.

Upvotes: 1

Related Questions