简体   繁体   English

如何将类的实例作为该类方法的参数传递?

[英]How do you pass an instance of a class as an argument for a method of that class?

Let's say I have this code. 假设我有这个代码。 When using an instance of ClassA, how do I pass the instance of the class to the method methodA ? 使用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);
    }
}

The way to achieve this is correct. 实现这一目标的方法是正确的。 Just use another name, because class is a reserved keyword for class definition 只需使用其他名称,因为class是类定义的保留关键字

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

Your approach works but you must not use the keyword class as a variable name. 您的方法有效,但您不能将关键字class用作变量名。 Try 尝试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将类传递给方法,并根据类的参数返回布尔值? - How do you pass a class into a method and return a boolean based on a parameter of the class? Java-如何将对象作为参数传递给该对象类的构造函数 - Java - How do you pass an object as an argument into a constructor from that objects class 您如何传递对“类”类型的引用? - How do you pass a reference to type 'class'? 如何在未将对象作为参数传递的方法中创建引用实例化类对象的对象? - How do I create an object referencing an instantiated class object inside a method that didn't pass the object as an argument? 如何模拟实例作为参数传递的类的非静态方法? - How to mock a non static method of a class whose instance is passed as argument? 如何创建实例变量以从另一个 class 调用非静态方法? - How do you create an instance variable to call a non-static method from another class? Java:如何指定类方法参数的类? - Java: How do I specify a class of a class method argument? 如何在.class文件中调用方法 - How do you call a method in a .class File 完成这个类方法 - 你知道怎么做吗? - Finish this class method - Do you know how? 如何将更新的全局类变量从一种方法传递到另一种方法? - How do you pass an updated global class variable from one method into another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM