0
Please explain this program
public class Vehicle { private String color; Vehicle() { this.setColor("Red"); } Vehicle(String c) { this.setColor(c); } // Setter public void setColor(String c) { this.color = c; } // Getter public String getColor() { return color; } } public class Program { public static void main(String[] args) { //color will be "Red" Vehicle v1 = new Vehicle(); //color will be "Green" Vehicle v2 = new Vehicle("Green"); System.out.println(v2.getColor()); } }
3 Answers
+ 3
To know more about constuctor, check this
https://beginnersbook.com/2013/03/constructors-in-java/
+ 2
In this class we have created a setter and getter method which is mainly use to set the value and get that value.
Here we have created two constructor. Constructor should same as class name.
1- Vehicle ()
2 - Vehicle (String c)
First type of constructor is called default constructor.
Second type of constructor called parameterized constructor. In this type of constructor we can pass any string value.
Now in main method we are creating two object of class to print the color. One object is creating by using simple constructor and Second object is creating by using parameterized constructor.
0
Please add Java in Relevant Tags đ