Constructor with parameter in java

Passing Information to a Method or a Constructor

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.

Parameter Types

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, as you saw in the computePayment method, and reference data types, such as objects and arrays.

Here’s an example of a method that accepts an array as an argument. In this example, the method creates a new Polygon object and initializes it from an array of Point objects (assume that Point is a class that represents an x, y coordinate):

public Polygon polygonFrom(Point[] corners) < // method body goes here >

Note: If you want to pass a method into a method, then use a lambda expression or a method reference.

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 (the previous method could have used varargs rather than an array).

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 Polygon polygonFrom(Point. corners) < int numberOfSides = corners.length; double squareOfSide1, lengthOfSide1; squareOfSide1 = (corners[1].x - corners[0].x) * (corners[1].x - corners[0].x) + (corners[1].y - corners[0].y) * (corners[1].y - corners[0].y); lengthOfSide1 = Math.sqrt(squareOfSide1); // more method body code follows that creates and returns a // polygon connecting the Points >

You can see that, inside the method, corners is treated like an array. The method can be called either with an array or with a sequence of arguments. The code in the method body will treat the parameter as an array in either case.

You will most commonly see varargs with the printing methods; for example, this printf method:

public PrintStream printf(String format, Object. args)

allows you to print an arbitrary number of objects. It can be called like this:

System.out.printf("%s: %d, %s%n", name, idnum, address);
System.out.printf("%s: %d, %s, %s, %s%n", name, idnum, address, phone, email);

or with yet a different number of arguments.

Читайте также:  Как перевернуть лист java

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:

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 PassPrimitiveByValue < 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 codeblock"> 
After invoking passMethod, x = 3

Passing Reference Data Type Arguments

Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.

For example, consider a method in an arbitrary class that moves Circle objects:

public void moveCircle(Circle circle, int deltaX, int deltaY) < // code to move origin of circle to x+deltaX, y+deltaY circle.setX(circle.getX() + deltaX); circle.setY(circle.getY() + deltaY); // code to assign a new reference to circle circle = new Circle(0, 0); >

Let the method be invoked with these arguments:

Inside the method, circle initially refers to myCircle . The method changes the x and y coordinates of the object that circle references (that is, myCircle ) by 23 and 56, respectively. These changes will persist when the method returns. Then circle is assigned a reference to a new Circle object with x = y = 0 . This reassignment has no permanence, however, because the reference was passed in by value and cannot change. Within the method, the object pointed to by circle has changed, but, when the method returns, myCircle still references the same Circle object as before the method was called.

Источник

Java Constructors

A constructor in Java is a special method that is used to initialize objects. The constructor is called when an object of a class is created. It can be used to set initial values for object attributes:

Example

// Create a Main class public class Main < int x; // Create a class attribute // Create a class constructor for the Main class public Main() < x = 5; // Set the initial value for the class attribute x >public static void main(String[] args) < Main myObj = new Main(); // Create an object of class Main (This will call the constructor) System.out.println(myObj.x); // Print the value of x > > // Outputs 5 

Note that the constructor name must match the class name, and it cannot have a return type (like void ).

Also note that the constructor is called when the object is created.

All classes have constructors by default: if you do not create a class constructor yourself, Java creates one for you. However, then you are not able to set initial values for object attributes.

Constructor Parameters

Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the constructor we set x to y (x=y). When we call the constructor, we pass a parameter to the constructor (5), which will set the value of x to 5:

Example

public class Main < int x; public Main(int y) < x = y; >public static void main(String[] args) < Main myObj = new Main(5); System.out.println(myObj.x); >> // Outputs 5 

You can have as many parameters as you want:

Example

public class Main < int modelYear; String modelName; public Main(int year, String name) < modelYear = year; modelName = name; >public static void main(String[] args) < Main myCar = new Main(1969, "Mustang"); System.out.println(myCar.modelYear + " " + myCar.modelName); >> // Outputs 1969 Mustang 

Источник

Parameterized Constructor in Java

Constructor

Parameterized constructors in Java are used to define states of the object during initialization. The parameterized constructors require one or more arguments to be passed during the initialization of an object. For "public" and "default" access modifiers, the access modifier of the constructor is the same as the access modifier of the class to whom the constructor belongs.

Follow the link to study constructors in Java.

What is Parameterized Constructor in Java

Parameterized constructors help to create objects with states defined by the programmer. Objects in java can be initialized with the default constructor or by a parameterized constructor. Initializing objects with parameterized constructors requires the same number and order of arguments to be passed by the user concerning the parameterized constructor being used. The objects created by using parameterized constructors can be unique with different data member values or states. One can have any number of parameterized constructors in a class. The parameterized constructors differ in terms of the parameters they hold. The compiler would not create a default constructor if the programmer creates their own constructor.

Why Parameterized Constructors are Used

Java class creates a default constructor if the programmer hasn't defined any type of constructor in the class. The parameterized constructor has to be defined explicitly by the programmer. The main aim to create parameterized constructor is to initialize the objects with programmer-defined states or values. The values of members can be assigned during the process of initializing the object with the help of parameterized constructors.

Examples

One can have any number of parameterized constructors in a class.

Example of Parameterized Constructor

In the below given parameterized constructor in java example, three constructors are implemented: one is the default constructor and the other two are parameterized constructors.

During initialization of an object, which constructor should get invoked depends upon the parameters one passes. For example when we create object like: namesClass n1=new namesClass("Krishna"); then the new keyword invokes parameterized constructor with string parameter (namesClass(String)) after object initialization.

Output

The above example demonstrates the use of one default and two parameterized constructors. The example shows that the type, order, and the number of arguments passed during the initialization of an object decide which constructor to invoke.

What is the return type of parameterized constructor in java?

Constructors have no return value, but the constructor returns the current instance of the class.

Error Thrown by Default Constructor

If programmer doesn't write any default constructor in the class, compiler inserts default constructor on its own. But if programmer has written any constructor in the class then compiler will not insert default constructor in that class.

Below two codes are examples demonstrating the same.

Example: 1

The above example, demonstrates the creation of default constructor by compiler when programmer hasn't written any constructor in the class.

Example: 2

The above example shows the error thrown by the use of default constructor as the compiler hasn't inserted any default constructor this time. The reason is that the user has already created one parameterized constructor in the class.

Differences Between Default Constructor and Parameterized Constructor in Java

Default Constructor Parameterized Constructor
Default constructor is 0 argument constructors which contain no-argument. Parameterized constructors have one or more than one arguments.
Main responsibility of default constructor is to assign default values to the newly created objects. Main aim of the parameterized constructors is to assign user-fed values to the instance variables of newly created objects.
Default constructor is created by compiler when the programmer doesn't write any constructor in the class. Parameterized constructor is specifically written by the programmer while creating a class.

Conclusion

  • Parameterized constructors in java are the programmer written constructors in a class which have one or more than one arguments.
  • Parameterized constructors are used to create user instances of objects with user defined states.
  • There can be more than one parameterized constructor in a class.
  • The compiler doesn't create any default constructor in a class if programmer writes one or more custom constructors.
  • Default constructor is created by compiler and has 0 arguments whereas parameterized constructor is specially written by programmer and has one or more than one arguments.

Источник

Оцените статью