kryz
kryz

Reputation: 99

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?

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

Upvotes: 2

Views: 809

Answers (2)

Antimon
Antimon

Reputation: 231

Your approach works but you must not use the keyword class as a variable name. Try

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

Upvotes: 1

azro
azro

Reputation: 54148

The way to achieve this is correct. Just use another name, because class is a reserved keyword for class definition

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

Upvotes: 3

Related Questions