Thursday 6 September 2018

Can I call one constructor from another in java?

Yes, you can call one constructor from other in Java using this().

Find the below working example.

Box.java

package com.sample.model;

public class Box {
 private int width;
 private int height;

 Box() {
  this(-1, -1);
 }

 Box(int width) {
  this(width, width);
 }

 Box(int width, int height) {
  this.width = width;
  this.height = height;
 }

 public int getWidth() {
  return width;
 }

 public void setWidth(int width) {
  this.width = width;
 }

 public int getHeight() {
  return height;
 }

 public void setHeight(int height) {
  this.height = height;
 }

}


You may like

No comments:

Post a Comment