Parameters and Arguments – Parameters are what we pass in variables in methods. We already seen this in previous examples:
Ex.
import java.lang.*;
public class VehicleMoving{
public static int gear;
public static int speed;
public VehicleMoving(int gear){
this.gear = gear;
}
public void accelerate(){
switch(gear){
case 1:
speed = 10;
System.out.println("the car is moving at " + speed);break;
case 2:
speed = 20;
System.out.println("the car is moving at " + speed);break;
}
}
public static void main(String[] args){
VehicleMoving car = new VehicleMoving(1);
car.accelerate();
VehicleMoving car2 = new VehicleMoving(2);
car.accelerate();
}
}
Vehicle constructor expects one argument which is (1) with the parameter gear. 1 is an integer, so it must have data types int vehicle (int gear).
Remember these Rules:
The method call or class instance of constructors must have the same number of arguments or parameters.
The arguments passed-in should have the same data type.
to be continued...
No comments:
Post a Comment