In this post, we will learn about Object and class in java. As Java is an object-oriented programming language, we need to design our program using Objects and classes.
Object:
An entity that has state and behavior may be termed as Object.
For example: Employee
has a state with name, age, and department, and behavior such as working on the assignment.
Class:
A class is a blueprint/template that defines state and behavior of objects.
For example: Employee
is a class in above example.
Object is an instance of class: As object are created on the basis of blueprint/template
that class provides, Object
is an instance of the class.
Let’s create a simple class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
package org.arpit.java2blog; public class Employee { String name; String age; public void workOnAssignment() { // Working on assignment } } |
Below diagram will explain the structure of class:
Let’ s see an example of Object now:
You can create object of above class as below:
Objects are stored in heap memory.
When above statement gets called, physical object is created in the memory as below:
Now let’s create two objects i.e. employee1 and employe2 and set name and age for these two objects.
1 2 3 4 5 6 7 8 |
Employee employee1=new Employee(); employee1.setName("Martin"); employee1.setAge(24); Employee employee2=new Employee(); employee2.setName("John"); employee2.setAge(20); |
These two objects will be created in memory as below:
Object is created using the constructor with the help of a new operator. We will see more about in subsequent tutorials.
that’s all about Object and class in java.