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

1

2 Answers 2

3

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

Truck(A a){
    ...
}
Truck(A a,B b){
    this(a);
    ...
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

or else google Constructor overloading and constructor chaining in Java
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;
    }
    ...
}

2 Comments

Excellent, this helped me out alot! I knew i was supposed to be doing something with this() but i wasnt sure what, having a complete example was what I needed.
@skulltula,have a nice day

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.