2017-04-25 8 views
0

私は、移動(移動(地球)と呼ぶ)を行うクラスでメソッドを持っていると言います。関数は、継承を使用して別のクラスで実装され、このようなものである:ランダマイズ関数の実装

animal.move(地球)

関数法いじりせずに実際の実装をランダム化することが可能ですか?

super.rMove(myEarth); 

全体の束があります:

public void rMove(Earth myEarth) throws InterruptedException 
{ 
    int x = (int) location.getX(); 
    int y = (int) location.getY(); 
    int xMax = myEarth.getX() - 1; 
    int yMax = myEarth.getY() - 1; 
    double w = Math.random(); 
    int rMove = (int) (w + Math.random()*4); 

    switch(rMove) 
    { 
     case NOR: 
      location.setLocation(x,y-1); 
      break; 
     case SOU: 
      location.setLocation(x,y+1); 
      break; 
     case EAS: 
      location.setLocation(x+1,y); 
      break; 
     case WES: 
      location.setLocation(x-1,y); 
      break; 
    } 
} 

このメソッドを含むクラスは、クラス肉食内の別のクラス

public class Carnivore extends Animal 

にこのような上記の関数を使用して動物の動きを拡張さ私はそれが関係しているとは思わない。私の質問は、実際のrMoveを変更せずに上記の実装を変更する方法です。

+0

ここまで行ったことの例を表示できますか?シグネチャを変更せずにメソッドの実装を変更することを意味しますか? – ACOMIT001

+0

私は自分の質問をmoveメソッドで更新しました。このクラスは別のクラスに拡張されているので、別のクラスのAnimalでこの関数を使用できます。私の質問は、元のメソッドを変更せずに関数Animal.Move(Earth)の実装を変更できますか? – AMR

+0

メソッドを変更せずにメソッドを変更したいですか?なぜそれが可能だと思いますか? – shmosel

答えて

0

私は、Animalのサブクラスによってオーバーライドできるランダム化ロジックのための別の方法があると考えます。私はJava開発者ではないので、構文が完全に正しくない可能性がありますが、これはあなたにアイデアを与えます。例:

public abstract class Animal 
{ 
    public abstract int moveRandom(); 
} 

public class Carnivore extends Animal 
{ 
    public int moveRandom() { 
     double w = Math.random(); 
     int rMove = (int) (w + Math.random()*4); 
     return rMove; 
    } 
} 


public void rMove() { 
    int rMove = this.rMove(); 
}