Implementing default parameter value in Java method
Those who already familiar with C++ will be missing default parameter values to a function call in Java. Here is the way of implementing same feature in Java.
In Java language , method can accept one or multiple object instance as parameters. Here idea is to pass one object instance instead of multiple primitive type parameters. This object will have default values set to all or some of the object members fields.
This explains how to implement the same by example. Here is an example of Simple Draw class as below.
Parameter Class :
package demo.graphics;
public class Option {
public Option() {
//Setting Default Parameters values
color = "BLACK";
lineWidth = 1;
pattern =0;
this.startX = 0;
this.startY = 0;
this.endX = 0;
this.endY = 0;
}
private String color;
private int lineWidth ;
private int startX;
private int startY;
private int endX;
private int endY;
private int pattern;
public Option(int startX, int startY, int endX, int endY){
this();
this.startX = startX;
this.startY = startY;
this.endX = endX;
this.endY = endY;
}
public Option(int startX, int startY, int endX, int endY,String color, int lineWidth, int pattern){
this();
this.startX = startX;
this.startY = startY;
this.endX = endX;
this.endY = endY;
this.color = color;
this.lineWidth = lineWidth;
this.pattern = pattern;
}
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setLineWidth(int lineWidth) {
this.lineWidth = lineWidth;
}
public int getLineWidth() {
return lineWidth;
}
public void setStartX(int startX) {
this.startX = startX;
}
public int getStartX() {
return startX;
}
public void setStartY(int startY) {
this.startY = startY;
}
public int getStartY() {
return startY;
}
public void setEndX(int endX) {
this.endX = endX;
}
public int getEndX() {
return endX;
}
public void setEndY(int endY) {
this.endY = endY;
}
public int getEndY() {
return endY;
}
public void setPattern(int pattern) {
this.pattern = pattern;
}
public int getPattern() {
return pattern;
}
}
Implementation Class :
package demo.graphics;
public class Draw {
public Draw() {
}
/**
* Draws line with given options
* @param option
*/
public static void drawLine(Option option){
//..
//..
}
public static void main(String[] args) {
//Constructing instance of Object class
Option opt1 = new Option(10,10,50,10);
//drawing line with above cordination and with default color,width and pattern
//as we haven't set their values here.
Draw.drawLine(opt1);
//drwing another line with custom color
Option opt2 = new Option(10,10,50,10);
opt2.setColor("RED");
//Here we are drawing line wih red color by over writing default value of color option
Draw.drawLine(opt2);
}
}
Comments
Post a Comment