I am given a class that has a private method say setCoors(int x, int y). The constructor of that class has the setCoors in it too. In a different class, I want to have a method setLocation which calls setCoors. Is this possible?
New Question:
If I am not allowed to set the method to public, is this possible?
public class Coordinate{
public Coordinate(int a, int b){
setCoors(a,b)
}
private void setCoords(int x, int y)
}
public class Location{
private Coordinate loc;
public void setLocation(int a, int b)
loc = new Coordinate(a,b)
}
No, private
means the method can only be called inside of the Class in which it is defined. You will probably want to have setLocation
create a new instance of the class setCoords
resides in, or change the visibility on setCoords
.
EDIT: The code you have posted will work. Just be aware that any instance of the Location
class will be bound to its own Coordinate
object. If you create a new Coordinate
object somewhere else in your code, you will be unable to modify its internal state. In other words, the line
Coordinate myCoord = new Coordinate(4, 5);
will create the object myCoord
which will forever have the coordinates 4
and 5
.