Search code examples
javareferenceinstanceclass-instance-variables

Java how to call method in another class


Sorry for the basic question but I'm learning, new to programming. I am trying to call a method that is in another class but I'm unable to without passing in the required values for the constructor of Cypher class. Do i really need a new instance of Cypher class each time i use a method in the Menu class and want to call a method of the Cypher class or how do I rewrite to avoid below.

public class Runner {
    private static  Cypher c;
    public static void main(String[] args)  {

        Menu m = new Menu();
        m.displayMenu();
        
        //c=new Cypher(3,2);// wont work unless i add this line
        c.displayCypher("text");

        
    }
}

public class Cypher {
    private int keyTotalRows;
    private int keyStartRow;
    
    
    public Cypher(int key, int offset) throws Exception {
        
        
    }

    
    public void displayCypher(String text) {
        
        System.out.println("Plain text:" + text);
        System.out.println("Key: Number of Rows:" + keyTotalRows + "\n" + "Key Start Row: " + keyStartRow);
        
    }
}

public class Menu {
            private Scanner s;
                private void enterKey() {
            s = new Scanner(System.in);
            System.out.println("Enter  key >");

            int key = Integer.parseInt(s.next());
            
            System.out.println("Enter offset >");

            int offset = Integer.parseInt(s.next());
            
            System.out.println(" Key:" + key + "\n" + " Offset:" + offset);

        }


        public static void displayMenu()  {
            System.out.println("Menu"); 
}

Solution

  • You declare a Cypher type static variable c here. so you can't access the Cypher class method using c variable without object declaration. But you can call the c variable from any class because it's a static variable. But your Cypher class don't have any static Method so you can't call these methods without object initialization. So you must declare a static method or need to create an object for the access method from Cypher class.

    But if you declare Cypher type static variable with initialization. then you can call c from any class and also called Chyper class method using the c variable reference. like:

    // Declare this on Runner class
    public static Cypher c = new Cypher();
    
    // And then call from any class like 
    Runner.c.yourMethod();
    

    Happy Coding.