5

I'm currently in a beginner java course at my university and am still learning the basics of programming. This week we've been learning about constructors, and I'm stuck on the second half of my assignment for this week so any help would be much appreciated.

the directions for the second part of the lab(the part i'm stuck on) are as follows:

Write the complete code for the class Truck as given in the class diagram below. Be sure to not use duplicate code in the constructors. For example, the constructors with 2 arguments should call the one with 1 argument to set the value for cylinder.

these are the constructors it wants me to make.

  • Truck()
  • Truck(int cylinders)
  • Truck(int cylinders, String manufacturer)
  • Truck(int cylinders, String manufacturer, double load)
  • Truck(int cylinders, String manufacturer, double load, double tow)

Any explanations/examples as to how to do this would be amazing

skulltula
  • 153
  • 1
  • 3
  • 10
  • i was going to close this as a duplicate of [How to avoid constructor code redundancy in Java](http://stackoverflow.com/questions/17171012/how-to-avoid-constructor-code-redundancy-in-java) – Nathan Hughes Sep 29 '15 at 17:46

2 Answers2

3

You can use this() to invoke another constructor. For eg:

Truck(A a){
    ...
}
Truck(A a,B b){
    this(a);
    ...
    ...
}
vivek
  • 231
  • 2
  • 14
0

just read a simple Oracle manual:

https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html or read stackoverflow.com more careful

public class Rectangle {
    private int x, y;
    private int width, height;

    public Rectangle() {
        this(0, 0, 1, 1);
    }
    public Rectangle(int width, int height) {
        this(0, 0, width, height);
    }
    public Rectangle(int x, int y, int width, int height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
    }
    ...
}
Community
  • 1
  • 1
Vyacheslav
  • 26,359
  • 19
  • 112
  • 194