- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Create Objects of a Class in Java
An object is created from a class using three steps i.e. declaration, instantiation, initialization. First the object is declared with an object type and object name, then the object is created using the new keyword and finally, the constructor is called to initialize the object.
A program that demonstrates object creation is given as follows −
Example
class Student { int rno; String name; void insert(int r, String n) { rno = r; name = n; } 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(); s.insert(101, "John"); s.display(); } }
The output of the above program is as follows −
Roll Number: 101 Name: John
Now let us understand the above program.
The Student class is created with data members rno, name and member functions insert() and display(). A code snippet which demonstrates this is as follows:
class Student { int rno; String name; void insert(int r, String n) { rno = r; name = n; } 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. Then insert() method is called with parameters 101 and “John”. Finally 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(); s.insert(101, "John"); s.display(); } }
- Related Articles
- Create class Objects in Java using new operator
- How to create class objects in Python?
- Different ways to create Objects in Java
- Create a queue using LinkedList class in Java
- Get the class name for various objects in Java
- 5 different ways to create objects in Java
- How to create immutable class in Java?
- Create a Date object using the Calendar class in Java
- How to create a LineBorder with BorderFactory class in Java?
- How to create wrapper objects in JShell in Java 9?
- How to create the immutable class in Java?
- How to create an immutable class in Java?
- Create empty border with BorderFactory class in Java?
- Is it possible to create a class without a name in Java?
- When should we create a user-defined exception class in Java?
