samedi 12 février 2022

Can a java object have attributes of a parent class object without duplicating the data

I am building an app with data "parent" classes that hold some attributes, and inheriting "child" classes that hold other attributes, but can also directly refer to the parent's attributes. The plan is to add some kind of unique prefix to the parent's attributes in the child to make sure there can be no name collisions with the child's attributes, but also more importantly to allow a child to extend more than one parent class.

Pseudocode would look something like this:

    public class Parent1{
        int a;
        public Parent1(int a){
            this.a=a;
        }
    }
    public class Parent2{
        int a;
        public Parent2(int a){
            this.a=a;
        }
    }
    public class Child{
        int b;
        public Child(int b,Parent1 p1,Parent2 p2){
            this.b=b;
            attributes.add("p1_"+p1.attributes);
            attributes.add("p2_"+p2.attributes);
        }
    }
    Child C=new Child(3,new Parent1(1),new Parent2(2));
    print(C.p1_a, C.p2_a, C.b);

The important thing to understand is that I want to avoid duplicating variables in memory, be able to use this with reflection so that I can access child s parent attributes from user input, as well as minimize code adjustments when adding new attributes to parents.

I understand that what I am trying to do could relatively easily be done by redefining each possible parent attribute in the child, essentially doing C.get_P1_A(), but I would like to avoid having to change the child code every time a new attribute gets added to a parent, and this would also complicate using reflection.

I have a suspicion what I am trying to do is impossible in Java (or at least I don't know a way to do it), so if that is the case, I am willing to drop being able to use reflection or not having to make adjustments while adding new attributes.





Aucun commentaire:

Enregistrer un commentaire