Parameters and Constructors

Functions with Parameters

It is possible to pass one or more values to a method when the method is called. As explained, a value passed to a method is called an argument. Inside the method, the variable that receives the argument is called a parameter. Parameters are declared inside the parentheses that follow the method’s name. The parameter declaration syntax is the same as that used for variables. A parameter is within the scope of its method, and aside from its special task of receiving an argument, it acts like any other local variable. Example is as follows:

class MethodTest2 {
	String MethodTest() // String is a return type of the Method MethodTest
	{
		return "It's great";
	}

	void MethodTest(int a) // no return type, parameters with function are used
	{
		System.out.println("a is " + a);
	}

	// this example also demonstrates the example of Method overloading as the
	// same method name is used for different type of arguments
}

public class ParametersInMethods {
	public static void main(String[] args) {
		MethodTest2 obj2 = new MethodTest2();
		System.out.println(obj2.MethodTest());
		obj2.MethodTest(100); // calling function with parameters
	}
}

Constructors

Constructors are the elements whose name if same as of class name in which they are defined and they are called automatically on Object creation. They are usually used for initializing the many elements according to need when it’s hectic to call member functions individually. Constructors with parameters are called as Parameterized Constructors. Example as follows:

class first {
	first() {
		System.out.println("called upon first creation");
	}

	first(String s) // Parameterized Constructors
	{
		System.out.println("Parameterized Constructors, parameter is " + s);
	}
}

public class ConstructorsExample {
	public static void main(String[] args) {
		first f = new first();
		first f1 = new first("good luck"); // calling Parameterized Constructors
	}
}