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,
privatemeans the method can only be called inside of the Class in which it is defined. You will probably want to havesetLocationcreate a new instance of the classsetCoordsresides in, or change the visibility onsetCoords.EDIT: The code you have posted will work. Just be aware that any instance of the
Locationclass will be bound to its ownCoordinateobject. If you create a newCoordinateobject somewhere else in your code, you will be unable to modify its internal state. In other words, the linewill create the object
myCoordwhich will forever have the coordinates4and5.