I'm just starting to learn OOP in Java, so this might be a dumb question. The Cat class extends Animal, they have a constructor, a static array, a method that fills the array, and a method that creates an object of the Moving class. On this created object of class Moving, the walk() method can be invoked. Question: how to write different behavior in the walk () method, depending on how the object was created (who was the creator Animal or Cat)? I was thinking of writing a separate efficiency() method to use in the walk() method, and put it in the Animal class and override this method in the Cat class. But in the walk() method, I can only use the static method of the Animal class and I can't override it for the Cat class.
If in Main I create Animal noName = new Cat(), then the program should call Cat.efficiency(). If I create Animal noName = new Animal(), then the Animal.efficiency() method must be called. Something like this, I think. Is it possible?
public class Animal {
private int capacity;
public static int[] animalArray;
public Animal(int value) {
animalArray = new int[value];
}
public boolean adSteps(int element){
if (capacity >= animalArray.length) {
return false;
} else {
animalArray[capacity++] = element;
}
return true;
}
public Moving letsMove() {
return new Moving();
}
public static int efficiency(int steps){
int equalSteps = steps+10;
return equalSteps;
}
}
public class Cat extends Animal{
public Cat(int value) {
super(value);
}
public static int efficiency(int steps) {
int equalSteps = steps + 50;
return equalSteps;
}
}
public class Moving {
private int[] movingArray = Animal.animalArray.clone();
private int totalWay;
public int walk(){
System.out.println("Go ahead");
for (int i = 0; i < movingArray.length; i++){
totalWay += movingArray[i];
}
totalWay = Animal.efficiency(totalWay);
return totalWay;
}
}
public class Main {
public static void main(String[] args) {
Animal noName = new Cat(3);
noName.adSteps(5);
noName.adSteps(3);
noName.adSteps(2);
Moving iAmMoving = noName.letsMove();
System.out.println(iAmMoving.walk());
}
}