Search code examples
javapointersmethodsparametersidentifier

Using pointers as parameter in method call in Java


I have the following problem:

When using a pointer as parameter in a method call I get the "error: identifier expected" error.

This is my code:

class Data {
    Person a = new Person("John");
    Person b = new Person("Mary");

    a.willHug(b);       // Gets error: <identifier> at this line
}

class Person {
    private String name;
    private Person hugs;

    Person(String n){
        this.name = n;
    }

    public void willHug(Person p) {
        hugs = p;
    }    
}

Solution

  • You shoul put this code inside of a method in order to execute it:

    For instance, the main method:

    class Data {
    
        public static void main(String args[]){
             Person a = new Person("John");
             Person b = new Person("Mary");
    
             a.willHug(b);       // Gets error: <identifier> at this line
    
        }
    }
    

    I think you should read this question of SO in order to understand better how parameters are passed in Java.

    Hope it helps.