有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从另一个类中的类调用方法

我的主要java代码如下所示:

package Javathesis;

//import... etc
//...


public class Javathesis; // My main class

{ 
    public static void // There are a lot of these classes here
    //...
    //...

    class x
    {
        String a;
        String b;

        x(String a, String b)
        {
            this.a = a;
            this.b = b;
        }
    }
    public void getAllDataDB1
    {
        ArrayList<ArrayList<x>> cells = new ArrayList<>();
        while(resTablesData1.next()) 
        {
            ArrayList<CellValue> row = new ArrayList<>();
            for (int k=0; k<colCount ; k++) {
            String colName = rsmd.getColumnName(i);
            Object o = resTablesData1.getObject(colName);
            row.add(new x(rsmd.getColumnType(),o.toString());
        }
        cells.add(row);
    }

    public static void main(String[] args) 
    {
        connectToDB1();
        // i want to call an instance of class "x" HERE!!!
    }
}

如何在公共静态void main中调用类x?我做错什么了吗?我已经测试了我知道的方法

Class class = new Class();
class.x(String a, String b);

但是我收到了错误。有人能帮我修一下吗? 提前谢谢


共 (4) 个答案

  1. # 1 楼答案

    此代码存在多个问题:

    Class class = new Class();
    class.x(String a, String b);
    

    不能将变量命名为“class”,它是一个保留字。另外,x是一个类——你不能仅仅调用它,你需要实例化它

    另外,为什么要实例化一个类——一个封装Java类知识的类

    类似的方法可能会奏效:

    Javathesis thesis = new Javathesis();
    Javathesis.x thesis_x = new thesis.x("a","b);
    

    另外,请用大写字母开头类名——这是Java中的惯例

  2. # 2 楼答案

    若要在不实例化该类中的对象的情况下调用类方法,必须将该方法声明为静态,然后使用类名dot method括号参数从任意位置调用该方法

    公共类x{

    //构造函数等

    公共静态整数加法(整数x,y){

    返回x+y

    }

    }

    //从其他地方打电话

    int y=x.add(4,5)

  3. # 3 楼答案

    您应该创建内部类的实例

    YourInnerClass inner = new YourOuterClass().new YourInnerClass(); 
    

    然后对其调用一个方法

    inner.doMyStuff();
    
  4. # 4 楼答案

    由于x是一个内部类,因此需要一个外部类实例来获取引用:

    Class x = new Javathesis().new x(a, b);
    

    此外,需要从类声明中删除分号

    可以使用创建的引用调用x中的方法

    Java命名约定显示类以大写字母开头。另外,给类一个比单个字母名称更有意义的名称也很好