1

maybe I've a serious gap in java fondamental comprehension. In the code below I can't understand how getLength method can calculate walk length. Why recall itself on tail?

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);
    }
}

2 Answers 2

1

You appear to be creating your own linked list, and the getLength() method iterates through the entire list, returning the full sum.

As an aside, please work on your code formatting for this site, especially your indentation.

Sign up to request clarification or add additional context in comments.

5 Comments

So exist only one instance of Move?
@StefanoMaglione: no, many instances of Move exist, and they are attached to each other in a linked-list.
In which variable they are attached and how variable tail can contain this chain?
@StefanoMaglione: please look at your own code. See which variable refers to the classes you're posting here.
Ah ok, tail in move W2 contain the chain?
0

It calculates the total length, from what I can tell.

return 1+tail.getLength();

This appears to say that the current object's walk length is 1, and it adds that to whatever tail walk length is. This gives the total length.

NOTE: Whoever wrote this, should look at the Java Naming Conventions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.