A class contains constructors that are invoked to create objects from the class.
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
For example, Bicycle has one constructor:
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
Bicycle myBike = new Bicycle(30, 0, 8);
Although Bicycle only has one constructor, it could have others, including a no-argument constructor:
public Bicycle() {
gear = 1;
cadence = 10;
speed = 0;
}
Both constructors could have been declared in Bicycle because they have different argument lists.
As with methods, the Java platform differentiates constructors on the basis of the number of arguments in the list and their types.
You cannot write two constructors that have the same number and type of arguments for the same class, because the platform would not be able to tell them apart.
Doing so causes a compile-time error.
You don't have to provide any constructors for your class, but you must be careful when doing this.
The compiler automatically provides a no-argument, default constructor for any class without constructors.
This default constructor will call the no-argument constructor of the superclass.
In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does.
If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.
You can use access modifiers in a constructor's declaration to control which other classes can call the constructor.
Note: If another class cannot call a MyClass constructor, it cannot directly create MyClass objects.
The declaration for a method or a constructor declares the number and the type of the arguments for that method or constructor.
For example, the following is a method that computes the monthly payments for a home loan, based on the amount of the loan, the interest rate, the length of the loan (the number of periods), and the future value of the loan:
public double computePayment(
double loanAmt,
double rate,
double futureValue,
int numPeriods) {
double interest = rate / 100.0;
double partial1 = Math.pow((1 + interest),
- numPeriods);
double denominator = (1 - partial1) / interest;
double answer = (-loanAmt / denominator)
- ((futureValue * partial1) / denominator);
return answer;
}
This method has four parameters: the loan amount, the interest rate, the future value and the number of periods.
The first three are double-precision floating point numbers, and the fourth is an integer.
The parameters are used in the method body and at runtime will take on the values of the arguments that are passed in.
Note: Parameters refers to the list of variables in a method declaration.
Arguments are the actual values that are passed in when the method is invoked. When you invoke a method, the arguments used must match the declaration's parameters in type and order.
You can use any data type for a parameter of a method or a constructor.
This includes primitive data types, such as doubles, floats, and integers,along with such as objects and arrays.
Arbitrary Number of Arguments You can use a construct called varargs to pass an arbitrary number of values to a method.
You use varargs when you don't know how many of a particular type of argument will be passed to the method.
It's a shortcut to creating an array manually
To use varargs, you follow the type of the last parameter by an ellipsis (three dots, ...), then a space, and the parameter name.
The method can then be called with any number of that parameter, including none.
public class Main
{
public static void main(String[] args) {
System.out.println("Hello World");
Main obj = new Main();
obj.add(2,3,4,5);
}
void add(int... a)
{
System.out.print(a[2]);
}
}
Above code gives output as 4. As an array is created and a[2] is used to store 4. But the same method is called even when no arguments are passed. But in this case would give a runtime error as arrayindexoutofbounds.
Parameter Names When you declare a parameter to a method or a constructor, you provide a name for that parameter. This name is used within the method body to refer to the passed-in argument.
The name of a parameter must be unique in its scope.
It cannot be the same as the name of another parameter for the same method or constructor, and it cannot be the name of a local variable within the method or constructor.
A parameter can have the same name as one of the class's fields.
If this is the case, the parameter is said to shadow the field.
Shadowing fields can make your code difficult to read and is conventionally used only within constructors and methods that set a particular field.
For example, consider the following Circle class and its setOrigin method:
public class Circle {
private int x, y, radius;
public void setOrigin(int x, int y) {
...
}
}
The Circle class has three fields: x, y, and radius. The setOrigin method has two parameters, each of which has the same name as one of the fields.
Each method parameter shadows the field that shares its name.
So using the simple names x or y within the body of the method refers to the parameter, not to the field.
To access the field, you must use a qualified name. This will be discussed later in this lesson in the section titled "Using the this Keyword."
Passing Primitive Data Type Arguments Primitive arguments, such as an int or a double, are passed into methods by value.
This means that any changes to the values of the parameters exist only within the scope of the method.
When the method returns, the parameters are gone and any changes to them are lost. Here is an example:
public class Main {
public static void main(String[] args) {
int x = 3;
// invoke passMethod() with
// x as argument
passMethod(x);
// print x to see if its
// value has changed
System.out.println("After invoking passMethod, x = " + x);
}
// change parameter in passMethod()
public static void passMethod(int x) {
x = 10;
System.out.println("Inside passMethod, x = " + x);
}
}
Output is:
Inside passMethod, x = 10
After invoking passMethod, x = 3