Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to set the values of one constructor with the values of another? [duplicate]

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

like image 750
skulltula Avatar asked Oct 19 '22 01:10

skulltula


1 Answers

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

Truck(A a){
    ...
}
Truck(A a,B b){
    this(a);
    ...
    ...
}
like image 99
vivek Avatar answered Oct 21 '22 20:10

vivek