Search code examples
javaoopprivateprogram-entry-point

How to Run private class method.in same class


Can figure why it won't allow me to run the displaymainMethod because it's private even though I know I can run it from from same class. Is there a way to do this without using reflective API?

This is the error

Error:(10, 9) java: cannot find symbol
  symbol:   class displayMainMenu
  location: class LoginPrototype

Code

import java.util.*;

public class LoginPrototype {

    public static void main(String[] args) {

        ArrayList<Credentials> allUsers = new ArrayList<Credentials>();
        displayMainMenu mainMenu = new displayMenu();
    }

    private void displayMainMenu() {
        int input;
        do {
            System.out.println("Menu Options");
            System.out.println("[1] Login");
            System.out.println("[2] Register");
            System.out.println("[0] Quit");//5 Displaying Main Menu Options
            Scanner sc = new Scanner(System.in);
            input = sc.nextInt();

            if (input > 2) {
                System.out.println("Please enter a value of [0] - [2]");
            }
            else if (input == 1){
                System.out.println("Login");
            }
            else if (input == 2){
                System.out.println("Register");
            }
            else if (input == 0){
                System.out.println("Thank you. bye.");
            }
        }while(input >= 2);
    }
}

Solution

  • There are several problems here.

    The first problem is the scope of your call. In the main method, you're trying to make a call to a method that requires an object reference. Main is static, displayMainMenu isn't. So, in order to call it, you need to instantiate a reference of the encapsulating class.

    The next problem is the method call. displayMainMenu() is a method, not a type. So the new keyword doesn't apply here.

    The next problem is the method's return type. displayMainMenu() has a return type of void. Void can't be assigned to a variable.

    Try to change it to:

    import java.util.*;
    
    public class LoginPrototype {
    
    public static void main(String[] args) {
    
        ArrayList<Credentials> allUsers = new ArrayList<Credentials>();
        LoginPrototype lp = new LoginPrototype();
        lp.displayMenu();
    }
    
    private void displayMainMenu() {
        //Do stuff
    }
    }
    

    That solves the major problems with the code.