- Get link
- X
- Other Apps
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.
AreaofRhombus Class |
In this class,
- We declared two variable of int type.
- The parameterized constructor "AreaOfRhombus" is defined with two parameters "p" and "q".
- 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.
- Constructor assigns the values of "p" and "q" to "pDiagnoal" and "qDiagonal" variables.
- The area() performs some calculations and returns the area.
"FindArea" Class |
- We created an object of "AreaofRhombus" class.
- 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.
- Then method area() calculates result using values passed here as parameters and returns result to "result" variable.
- The print statements prints the value of result on screen.
Output:
Output of Program |
Experiment: Try finding out area of rectangle, triangle and circle using parameterized constructors.
Happy Coding!
Comments
Great work
ReplyDeleteThanks
Delete