Scanner class Methods in Java

Parameterized Constructor

Parameterized Constructor

This is the second type of Constructor. In the last post, we discussed Default Constructor.This is very useful in making programs where we require to call other classes with some data.

The constructor which can contain parameters like normal method is known as Parameterized constructor.We can specify parameters in its definition within parenthesis (). This constructor set class variables to value of parameters passed from other class to it. In other words, we can initialize current class's variable from other class using parameterized constructor.

Syntax:

public ConstructorName(dataype param1, datatype param2, ......, dataype paramn)

{

//constructor body

}

In the syntax,ConstructorName must be same as class name.In the parenthesis, define variables that are used by constructor. The dataype is the type of parameters like int,float,double,String etc. And param1, param2 are dummy names of parameters.You can give any name to them.In constructor body we can write statements to initialized variables of class.

for example:

public MyClass(int a, String b,float c)

{

//statements here

}

Example: This will illustrate the use of parameterized constructor.

Write a program to caculate Area of Rhombus using parameterized constructor.

example of parameterized constructor
AreaofRhombus Class

In this class,

  1. We declared two variable of int type.
  2. The parameterized constructor "AreaOfRhombus" is defined with two parameters "p" and "q".
  3. In the body of constructor, we are using this keyword. The this keyword is used in reference to this class's variables.It is used to refer that variables which are following it belong to this particular class.Which means, this keyword is referring to AreaOfRhombus class.
  4. Constructor assigns the values of "p" and "q" to "pDiagnoal" and "qDiagonal"  variables.
  5. The area() performs some calculations and returns the area.
example of parameterized constructor
"FindArea" Class
We created this class with main method.This class will execute and show the result on screen.In this class,

  1. We created an object of "AreaofRhombus" class.
  2. While generating object "ar" we are passing some values to constructor as 4 and 5,These values goes to AreaOfRhombus constructor definition and get assigned to "pDiagonal" and "qDiagonal" variable.
  3. Then method area() calculates result using values passed here as parameters and returns result to "result" variable.
  4. The print statements prints the value of result on screen.
Output:
example of parameterized constructor
Output of Program


This way we can use these constructors.They are useful while creating larger programs or software.

Experiment: Try finding out area of rectangle, triangle and circle using parameterized constructors.

Happy Coding!


Comments

Post a Comment

If you have any doubt, ask here