user8678484
user8678484

Reputation:

Java, how to merge smaller classes via 1 big class?

Imagine having the following classes:

Head
Torso
Hands
Legs

that I would like to keep but link them via a new class Human. This is what their codes look like:

package myEntities;

public class Head {

    private float headSize;

    Head(float headSize) {
        this.headSize = headSize;
    }

    public static void main(String[] args) { }

    public float[] getHeadSize() {
        return headSize;
    }
}

repeated the same for the other 3 parts except for the name. If I wanted to make a human class, how would it look like? I'm thinking something like this but this seems too repetitive:

package myEntities;

public class Human {

    private Head headObject = new Head(variable1);
    private Torso torsoObject = new Torso(variable2);
    private Leg rightLegObject = new Leg(variable3);


    Human(float variable1, float variable2, float variable3) {

    }



    public static void main(String[] args) { }

And this way gives an error of not being able to resolve variable1 and the rest of the variables.

Upvotes: 0

Views: 95

Answers (1)

ControlAltDel
ControlAltDel

Reputation: 35061

First, in your human class, the constructor should be a Human constructor (not a Zombie - Zombie could be a superclass, a subclass, or a completely separate class)

public class Human {

    Human(float variable1, float variable2, float variable3) {

    }
}

Second, you need to declare the object members like you are doing, but initialize them in your constructor

Human {
    private Head headObject;
    private Torso torsoObject; 
    private Leg rightLegObject;

    public Human (float variable1, float variable2, float variable3) {
      headObject = new Head(variable1);
      torsoObject = new Torso(variable2);
      rightLegObject = new Leg(variable3);
   }
}

Upvotes: 1

Related Questions