
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
Class with a Constructor to Initialize Instance Variables in Java
A class contains a constructor to initialize instance variables in Java. This constructor is called when the class object is created.
A program that demonstrates this is given as follows −
Example
class Student { private int rno; private String name; public Student(int r, String n) { rno = r; name = n; } public void display() { System.out.println("Roll Number: " + rno); System.out.println("Name: " + name); } } public class Demo { public static void main(String[] args) { Student s = new Student(173, "Susan"); s.display(); } }
The output of the above program is as follows −
Roll Number: 173 Name: Susan
Now let us understand the above program.
The Student class is created with data members rno, name. The constructor Student() initializes rno and name. The member function display() displays the values of rno and name. A code snippet which demonstrates this is as follows:
class Student { private int rno; private String name; public Student(int r, String n) { rno = r; name = n; } public void display() { System.out.println("Roll Number: " + rno); System.out.println("Name: " + name); } }
In the main() method, an object s of class Student is created with values 101 and “John”. Then the display() method is called. A code snippet which demonstrates this is as follows:
public class Demo { public static void main(String[] args) { Student s = new Student(173, "Susan"); s.display(); } }
Advertisements