Class and objects in Java
Let’s understand Class and objects in Java
Class
Class
represents a real world entity which has both state and behavior which is applicable to all the objects of this Class.
So Class
is called as a blue print or a template using which each object will be created.
Example:
Create Student.java
- Class Student{
- String id;
- int age;
- String course;
- Void enroll(){
- //Logic for enrolling student
- System.out.println("Student enrolled");
- }
- }
Class Student{ String id; int age; String course; Void enroll(){ //Logic for enrolling student System.out.println("Student enrolled"); } }
In the above class, we have a real world entity called “Student” which is represented by a class with its states
like id,age and course and also behavior
like enroll.
A class
will have local variables, instance variables and static variables and we need to have very clear understanding of these variables to use them as per the requirement.
Check Variables in Java article to understand the same.
A class
can have any number of methods depending on our requirement.
In the above example, we have added only one method called “ enroll() “.
Object
Object
is an instance of class and generally objects are created using the constructor
.
Each object holds the state and behavior specific to it
We can create any number of objects using a class
and hence class is sometime referred as collection of objects.
Let’s create an Object of Student class as below
- Student s1 = new Student();
Student s1 = new Student();
Now object
is created and is referred by the reference variable called “s1”.
Once the object
is created, we can use its reference variable to access the attributes and methods based on the access level defined.
Check Heap and Stack article to understand where these objects gets created in Java
Check access modifiers article to understand various access levels used in the class
We can set the state of this object as below
- s1.id=123;
- s1.age=18;
- s1.course=”computers”;
s1.id=123; s1.age=18; s1.course=”computers”;
We can access the method to enroll this “s1” student as below
- s1.enroll();
s1.enroll();
Complete example is as below
Student.java
- Class Student{
- String id;
- int age;
- String course;
- Void enroll(){
- //Logic for enrolling student
- System.out.println("Student enrolled");
- }
- }
Class Student{ String id; int age; String course; Void enroll(){ //Logic for enrolling student System.out.println("Student enrolled"); } }
StudentManager.java
- Class StudentManager{
- public static void main(String []args) {
- Student s1 = new Student();
- s1.id=123;
- s1.age=18;
- s1.course=”computers”;
- s1.enroll();
- }
- }
Class StudentManager{ public static void main(String []args) { Student s1 = new Student(); s1.id=123; s1.age=18; s1.course=”computers”; s1.enroll(); } }