Java如何在另一个类中调用方法 [英] Java how to call method in another class

查看:64
本文介绍了Java如何在另一个类中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉出现了基本问题,但我正在学习,这是编程的新手.我正在尝试调用另一个类中的方法,但是我无法不传递 Cypher 类的构造函数所需的值.每次使用 Menu 类中的方法并想调用 Cypher 的方法时,我是否真的需要 Cypher 类的新实例吗?类或如何重写以避免出现在下面.

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

推荐答案

您在此处声明了Cypher类型的静态变量 c .因此,如果没有对象声明,就无法使用 c 变量访问Cypher类方法.但是您可以从任何类中调用 c 变量,因为它是静态变量.但是您的Cypher类没有任何静态方法,因此,如果没有对象初始化,就无法调用这些方法.因此,您必须声明一个静态方法,或者需要为Cypher类中的访问方法创建一个对象.

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.

但是如果您通过初始化声明Cypher类型的静态变量.那么您可以使用 c 变量引用从任何类调用c,也可以调用Chyper类方法.像:

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

快乐编码.

这篇关于Java如何在另一个类中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆