dimanche 28 mai 2017

Setting super properties using abstract subclasses

Is it ok(for java and SOLID principals) to extend abstract classes in order to set properties from the super class? What I want to achieve is to apply different values to p2 depending on what p1 has and also p3 values will depend of what the value of p2 is(something similar when you cascade drop down menus). Could this scenario be dealt with a design pattern?

public interface Iface{
    public void set_p1(int i);
    public void set_p2(int i);
    public void set_p3(int i);
}

public abstract class A implements Iface{
    private int p1;
    private int p2;
    private int p3;

    public void set_p1(int i){
        this.p1 = i;
    }

    public void set_p2(int i){
        this.p2 = i;
    }

    public void set_p3(int i){
        this.p3 = i;
    }
}

Here I set p1 to 100

public abstract class setOne extends A {
    public setOne(){
        set_p1(100);
}

now I set p2 depending on the values of p1

public abstract class setTwo extends setOne {
    public setTwo(){
        //do some work using p1
        set_p2(200);
}

now I instantiate my setTwo abstract class

public class TestClass extends setTwo {
    public TestClass(){
         super();
}

TexClass myObj =  new TestClass();

now I expect the values of the object as follows:

myObj.p1 = 100

and

myObj.p2 =  200;

Aucun commentaire:

Enregistrer un commentaire