2014-02-15 24 views
1

也許我在java fondamental理解方面存在嚴重的空白。在下面的代碼中,我無法理解getLength方法如何計算步行長度。爲什麼回想起尾巴?理解java方法的問題

class Point { 

    private int x; 
    private int y; 

    public Point(int x, int y) { 
     this.x = x; 
     this.y = y; 
    } 

    public static void main(String argv[]) { 

     Point p1 = new Point(0, 0); 
     // Walk w1 = new Right(new Down(new Left(new Up(new Stop())))); 
     Move w2 = new Left(new Left(new Up(new Stop()))); 
     // Walk w3=new Right(new Stop()); 
     System.out.println(w2.tail); 
    } 
} 

abstract class Walk { 

    public abstract boolean isStop(); 

    public abstract int getLength(); 
} 

class Stop extends Walk { 

    @Override 
    public boolean isStop() { 
     return true; 
    } 

    @Override 
    public int getLength() { 
     return 0; 
    } 
} 

abstract class Move extends Walk { 

    Walk tail; 


    @Override 
    public int getLength() { 

     return 1 + tail.getLength(); 
    } 

    Move(Walk tail) { 
     this.tail = tail; 

    } 

    @Override 
    public boolean isStop() { 
     return true; 
    } 
} 

class Right extends Move { 

    public Right(Walk tail) { 

     super(tail); 

    } 
} 

class Left extends Move { 

    public Left(Walk tail) { 
     super(tail); 
    } 
} 

class Up extends Move { 

    public Up(Walk tail) { 
     super(tail); 
    } 
} 

class Down extends Move { 

    public Down(Walk tail) { 
     super(tail); 
    } 
} 

回答

1

你似乎是創建自己的鏈表,並在整個列表中getLength()方法循環,​​恢復完整的總和。

另外,請爲您的代碼格式化本網站,特別是縮進。

+0

因此只存在Move的一個實例? –

+0

@StefanoMaglione:不,Move的許多實例存在,並且它們在鏈接列表中彼此連接。 –

+0

它們在哪個變量中連接,以及變量尾部如何包含此鏈? –

0

它根據我所知道的來計算總長度。

return 1+tail.getLength(); 

這似乎說,當前對象的步行路程長度爲1,並補充說,到任何tail步行路程長度。這給出了總長度。

注意:誰寫了這個,應該看Java Naming Conventions