Search code examples
javaoopcomposition

How to prune an object of some of its fields in Java?


Suppose we have an object obj of type Object such that System.out.println(obj) produces {a=Some text, b=Some more text, c=Even more text}.

Now we want to make a new object obj2 that is just {a=Some text} (i.e., the fields b and c are pruned from obj). So we define a class A as follows:

class A {
    String a;
}

Then we initialize obj2 as follows:

A obj2 = (A) obj.

Unfortunately, I get a run time error when doing this.

Question: How do we define obj2 as outlined above?


Solution

  • Assume that you have three fields f1,f2,f3 in class A

    Create a new class B with field f1

    Declare a method in class A like this

    public B getTrimmedObject()
    

    Set required fields of B from A.

    e.g. set f1 and return B Object

    Other way : use composition over inheritance.B will become member of A and you can simply get B from A. In this case split fields between A and B and avoid duplication.

    f1 will be part of B and B,f2,f3 will be part of A. A Constructor will set f1 value through B and f2,f3 are set with normal initialization

    EDIT: example code:

    public class A{
        private B b;
        private String f2;
        private String f3;
    
        public A(String f1,String f2,String f3){
            b = new B(f1);
            this.f2 = f2;
            this.f3 = f3;
            System.out.println("In A->B:"+getB().getF1()+":A:f2:"+f2+":A:f3:"+f3);
        }
        public B getB(){
            return this.b;
        }
        public static void main(String args[]){
            if (args.length < 3) {
                System.out.println("Usage: java A str1 str2 str3");
                return;
            }
            A a = new A(args[0],args[1],args[2]);
    
        }
    
    }
    class B{
        private String f1;
        public B(String f1){
            this.f1 = f1;
        }
        public String getF1(){
            return this.f1;
        }
    }
    
    
    
    java A apple banana camel
    
     In A->B:apple:A:f2:banana:A:f3:camel