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
Create class Objects in Java using new operator
Class objects can be created in Java by using the new operator. A class is instantiated by the new operator by allocating memory for the object dynamically and then returning a reference for that memory. A variable is used to store the memory reference.
A program that demonstrates this is given as follows:
Example
class Student {
int rno;
String name;
public Student(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(15, "Peter Smith");
s.display();
}
}
Output
Roll Number: 15 Name: Peter Smith
Now let us understand the above program.
The Student class is created with data members rno, name. A constructor initializes rno, name and the method display() prints their values. A code snippet which demonstrates this is as follows:
class Student {
int rno;
String name;
public Student(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 by using the new operator. 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(15, "Peter Smith");
s.display();
}
}Advertisements