Constructors are used to initialize our variables but this is optional. As I've said, there is already a default constructor created for us.
Ex.
public class Vehicle{
public Vehicle(int wheels){
this.wheels = wheels;
}
}
There are rules in creating constructors:
It should have the same name as your class.
It does not have a return type.
You can create as many constructors provided you must have different number of parameters or different type.
Ex.
public class Vehicle{
public Vehicle(int wheels){
}
public Vehicle(String color, int doors){
}
public Vehicle(int gears, int steeringwheels){
}
}
Note: It is recommended you use different name for your parameters from the class variables.
Ex.
public class Vehicle{
public int trunk;
public String type;
public Vehicle(int wheels, int gears){
trunk = 1;
type = “car”;
wheels = 4;
gears = 6;
}
}
If you have same variable names for your parameters and class variables use the keyword “this.”
Ex.
public class Vehicle{
public int wheels;
public int gears;
public Vehicle(int wheels, int gears){
this.wheels = wheels;
this.gears = gears;
}
}
to be continued...
No comments:
Post a Comment