Code a class called tree, code an overloaded constructor that accepts tree name, width and height. the overloaded will print "rainbow" "6ft""200 ft" JAVA
Java code for creating the class and the overloaded constructor as mentioned in the question with the comments above is below :-
public class tree //tree class with the variable members
defined
{
String tree_name;
String tree_width;
String tree_height;
tree() //Default constructor without parameters
{
tree_name = "Papaya";
tree_width = "8ft";
tree_height = "200 ft";
}
tree(String name, String width, String height) //constructor with
the parameters
{
tree_name = name;
tree_width = width;
tree_height = height;
}
public String gettreeName()
{
return tree_name;
}
public String gettreeWidth()
{
return tree_width;
}
public String gettreeheight()
{
return tree_height;
}
public static void main(String args[])
{
//object creation and calling the constructor without
parameter
tree obj1 = new tree();
//object creation and calling the constructor with parameters
tree obj2 = new tree("rainbow", "6ft", "200 ft");
System.out.println("tree name is: " + obj2.gettreeName());
System.out.println("tree width is: " + obj2.gettreeWidth());
System.out.println("tree height is: " +
obj2.gettreeheight());
}
}
Explanation :-
Overloaded constructor : Overloaded constructors are when more than one constructor are being defined with different signatures i.e. no or different parameters defined . Overloaded constructors have the same name but have different parameter signatures defined . For example , one constructor can have no parameters , second can have one parameter passed , third can have two or more parameters defined and so on .
In the above example following are the execution points :-
1) When the control goes to the main method in the class tree , there first an object obj1 is created which calls the constructor with the name tree which has no arguments passed to it . In that constructor the values to the name , width , height are set as "Papaya" , "8ft" , "200 ft". But they are not printed as using the object obj1 the get methods are not called in the pritnln statement .
2) Next the second object obj2 is created which calls the constructor in which the parameters are defined . Therefore , when the constructor is called the values are passed and are assigned to the member variables of the class tree i.e. tree_name , tree_width , tree_height . Then the three println statements are executed in which the values of the passed parameters ie. name , width , height are printed by calling the get method using the second object i.e. obj2 . Therefore in the display screen the values rainbow , 6ft , 200 ft are printed .
Screenshot of the above code execution :-


Code a class called tree, code an overloaded constructor that accepts tree name, width and height....