-1
    public class Agent {
        private Space _location;
        private String _name;
        public void setLocation(Space space){
            _location = space;
        }
        public void usePortal(){
            if(_location.getPortal() != null){
            Portal.transport(Agent.this);
            }
        }
    }

java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method transport(Agent) from the type Portal

Above is the error it gives me. I have a public class Space with a member variable of type Portal and a getPortal() getter. which looks like:

    public class Space {
        private String _name;
        private String _description;
        private Portal _portal;
        public Portal getPortal(){
            return _portal;
        }
    }

In my public Portal class, I have a transport method with an Agent parameter:

    public class Portal {
        private String _name;
        private String _direction;
        private Space _destination;
        public Space getDestination(){
            return _destination;
        }
        public void transport(Agent str){
            str.setLocation(getDestination());
        }
    }

My main problem is having the usePortal() method to work, the Space and Portal classes are fully functional. I don't know how I would call the method on an instance of Agent within the Agent class.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
Ortech
  • 21
  • 3

3 Answers3

1

java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method transport(Agent) from the type Portal

This is because transport method is an instance method and not static.

Either create an instance of Portal and then use that or make the transport method static

Portal portal = new Portal();
portal.transport(this);

or

public static void transport (Agent str)

I don't know how I would call the method on an instance of Agent within the Agent class.

Instead of Agent.this use just this

Ajay George
  • 11,759
  • 1
  • 40
  • 48
1

You can't call other class methods without initializing an object reference. Unless it is declared static.

For example:

Portal portal = new Portal();
portal.transport(this);

Note that this is a reference to the current object, in this case, Agent.

Do some more research online to see how java objects work and also research static and non-static contexts. Tons of examples!

proulxs
  • 498
  • 2
  • 13
0

this should work

public void usePortal(){
    if(_location.getPortal() != null){
    _location.getPortal().transport(this);
    }
}
Anshul
  • 159
  • 1
  • 10