I wrote the following code:

package com.chain;

public interface Chain {
    void setNext(Chain chain);
    void process(int number);
}


package com.chain;

public class ProcessNegative implements Chain{
    private Chain chain;

    public void setNext(Chain chain){
        this.chain = chain;
    }
    public void process(int number){
        if(number < 0){
            System.out.println("Negative");
        }else{
            chain.process(number);
        }
    }
}


package com.chain;

public class ProcessPositive implements Chain{
    private Chain chain;

    public void setNext(Chain chain){
        this.chain = chain;
    }
    public void process(int number){
        if(number>0){
             System.out.println("Positive");
        }else{
            chain.process(number);
        }
    }
}


package com.chain;

public class ProcessZero implements Chain{
    private Chain chain;

    public void setNext(Chain chain){
        this.chain = chain;
    }
    public void process(int number){
        if(number==0){
             System.out.println("Positive");
        }else{
            chain.process(number);
        }
    }
}


package com.chain;

public class Test {
    public static void main(String[] args){
        Chain c1 = new ProcessNegative();
        Chain c2 = new ProcessZero();
        Chain c3 = new ProcessPositive();
        c1.setNext(c2);
        c2.setNext(c3);
        c1.process(-1);
        c2.process(5);
        c3.process(1);
    }
}

If I change c3 process value from 1 to -1, I get an exception. Isn't other objects in the chain suppose to process the value?

Your help is kindly appreciated.

Thank You.

Recommended Answers

All 3 Replies

" I get an exception"

We're not going to guess what that could be. Exactly what exception at which line? - copy/paste complete message

... but anyway, c3 is the end of the chain, you didn't define a "next" for it, so on line 39 chain will be null... -> exception!

You are right that c2 is the end of the chain. So I defined a next for it and it works. Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.