
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Parametrized Constructors in Java
A constructor is similar to method and it is invoked at the time creating an object of the class, it is generally used to initialize the instance variables of a class. The constructors have same name as their class and, have no return type.
Parameterized constructors
A parameterized constructor accepts parameters with which you can initialize the instance variables. Using parameterized constructor, you can initialize the class variables dynamically at the time of instantiating the class with distinct values.
Syntax
public class Sample{ Int i; public sample(int i){ this.i = i; } }
Example
public class Test { String val; Test(String val){ this.val = val; } public static void main(String args[]){ Test obj = new Test("test"); System.out.println(obj.val); } }
Output
test
Example
import java.util.Scanner; public class Test { int num; String data; float flt; Test(int num, String data, float flt){ this.num = num; this.data = data; this.flt = flt; } public static void main(String args[]){ Scanner sc = new Scanner(System.in); System.out.println("Enter an integer value: "); int num = sc.nextInt(); System.out.println("Enter a string value: "); String data = sc.next(); System.out.println("Enter a floating point value: "); float flt = sc.nextFloat(); Test obj = new Test(num, data, flt); System.out.println(obj.num); System.out.println(obj.data); System.out.println(obj.flt); } }
Output
Enter an integer value: 1024 Enter a string value: test Enter a floating point value: 11.2 1024 test 11.2
Advertisements