Getters and Setters
- Getter: Returns the value.
- Setter: Sets/updates the value.
- Getter and setter are methods used to protect our data and make our code more secure.
- To protect our data, we make our variables private in a class. So these variables can't be accessed directly outside the class. So we use getters and setters to set the value of that variable and to return the value of that variable.
Output :
Enter your name: Deepak Chandra Sharma
Enter your roll no: 38
Enter your marks: 92.6
Enter your contact number: 8791304163
Printing details of student 1...
Student Name: Pankaj Singh Negi
Student Roll No: 25
Student Marks: 95.6
Student Phone Number: 7249926519
Printing details of student 2...
Student Name: Deepak Chandra Sharma
Student Roll No: 38
Student Marks: 92.6
Student Phone Number: 8791304163
To invoke current class constructor and method.
To return the current class instance.
Constructors
- A constructor in Java is a special method that is used to initialize objects.
- Constructors do not return any type of data i.e. that do not have any return data type.
- Every time an object is created using new() keyword, at least one constructor is called.
- If we do not create a constructor by yourself, then a default constructor (created by Java compiler) is called.
Rules for creating a Constructor
- The constructor name should be same as the class name.
- It must have no explicit return type.
- We can use access modifiers while declaring a constructor, but a Java constructor cannot be abstract, static, final and synchronized.
Types of Constructors
- Default constructor: A constructor with zero parameters is called a default constructor.
The default constructor is used to provide the default values to the object like 0, null etc., depending on the type. - Parameterized constructor: A constructor which has a specific number of parameters is called a parameterized constructor.
The parameterized constructor is used to provide different values to distinct objects. However, we can provide the same values also.
Output :
Enter your name: Deepak Chandra Sharma
Enter your marks: 92.6
Enter your phone number: 8791304163
Printing details of student 1...
Student Name: Satyam Chaurasia
Student Roll No: 420
Student Marks: 98.9
Student Phone Number: 8299416025
Printing details of student 2...
Student Name: Deepak Chandra Sharma
Student Roll No: 38
Student Marks: 92.6
Student Phone Number: 8791304163
Printing details of student 3...
Student Name: Aviskar Chaudhary
Student Roll No: 21
Student Marks: 95.4
Student Phone Number: 9454978593
Comments
Post a Comment