【问题标题】:How do you pass an instance of a class as an argument for a method of that class?如何将类的实例作为该类方法的参数传递?
【发布时间】:2019-03-26 00:29:27
【问题描述】:

假设我有这个代码。使用 ClassA 的实例时,如何将类的实例传递给方法methodA

public class ClassA {

    public static int methodA(ClassA class) {

        return 1;
    }
}

//This is wrong but this is what I'm trying to do
public class Main {

    public static void main(String [] args) {

        ClassA classa = new ClassA();
        classa.methodA(classa);
    }
}

【问题讨论】:

    标签: java class parameters arguments instance


    【解决方案1】:

    实现这一点的方法是正确的。换个名字就行了,因为class是类定义的保留关键字

    public static int methodA(ClassA instance) {
        return 1;
    }
    

    【讨论】:

    • 如果我想从methodB调用methodA怎么办?有没有办法做到这一点?
    • @kryz 和 doe methodB 看起来像?
    【解决方案2】:

    您的方法有效,但您不能使用关键字class 作为变量名。试试

    public class ClassA {
        public static int methodA(ClassA clazz) {
            return 1;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-05
      • 2020-01-26
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 2015-01-22
      • 2019-05-24
      相关资源
      最近更新 更多