I think this is not a task to be solved in a single class. From an object-oriented perspective (which should be taken when programming in Java), you are in need of at least 3 classes, which are Location, FourLeggedAnimal and a main class, let's say FourLeggedMain:
An animal should look like this when it is named and in a location:
package fourlegs;
public class FourLeggedAnimal {
protected String name;
protected Location location;
public FourLeggedAnimal(String name, Location room) {
this.name = name;
this.location = room;
}
public Location getLocation() {
return location;
}
public void follow(FourLeggedAnimal animal) {
this.location = animal.getLocation();
}
public void moveTo(Location room) {
this.location = room;
}
public String getCurrentLocation() {
return location.getName();
}
}
The location just needs a name:
package fourlegs;
public class Location {
private String name;
public Location(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And the main performs the logic including the other objects:
package fourlegs;
public class FourLegsMain {
public static void main(String[] args) {
Location office = new Location("office");
Location carpark = new Location("carpark");
FourLeggedAnimal cat = new FourLeggedAnimal("cat", office);
FourLeggedAnimal dog = new FourLeggedAnimal("dog", office);
System.out.println("The cat is at the " + cat.getCurrentLocation());
System.out.println("The dog is at the " + dog.getCurrentLocation());
dog.moveTo(carpark);
System.out.println("The dog went to the " + dog.getCurrentLocation());
System.out.println("The cat is still at the " + cat.getCurrentLocation());
cat.follow(dog);
System.out.println("The cat followed the dog and is at the "
+ cat.getCurrentLocation()
+ " now");
}
}
Executing it will provide the following output:
The cat is at the office
The dog is at the office
The dog went to the carpark
The cat is still at the office
The cat followed the dog and is at the carpark now
catis declared in the methodstart(), that means it is only available in the scope of that method. Declare it as a class attribute (likeroom) and you can use it in all methods of the class.moveondogalso affectcat?