In this page, we will learn about Java objects and classes. In object-oriented programming technique, we design a program using objects and classes.
An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system.
An object has three characteristics:
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
class <class_name>{ field; method; }
A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable.
In Java, a method is like a function which is used to expose the behavior of an object.
The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area.
In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value.
Here, we are creating a main() method inside the class.
File: Student.java
//Java Program to illustrate how to define a class and fields //Defining a Student class. class Student{ //defining fields int id;//field or data member or instance variable String name; //creating main method inside the Student class public static void main(String args[]){ //Creating an object or instance Student s1=new Student();//creating an object of Student //Printing values of the object System.out.println(s1.id);//accessing member through reference variable System.out.println(s1.name); } }
In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method.
File: TestStudent1.java
//Java Program to demonstrate having the main method in //another class //Creating Student class. class Student{ int id; String name; } //Creating another class TestStudent1 which contains the main method class TestStudent1{ public static void main(String args[]){ Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } }
There are 3 ways to initialize object in Java.
Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable.
File: TestStudent2.java
class Student{ int id; String name; } class TestStudent2{ public static void main(String args[]){ Student s1=new Student(); s1.id=101; s1.name="Sonoo"; System.out.println(s1.id+" "+s1.name);//printing members with a white space } }
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
class Student{ int id; String name; } class TestStudent3{ public static void main(String args[]){ //Creating objects Student s1=new Student(); Student s2=new Student(); //Initializing objects s1.id=101; s1.name="Sonoo"; s2.id=102; s2.name="Amit"; //Printing data System.out.println(s1.id+" "+s1.name); System.out.println(s2.id+" "+s2.name); } }
In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java
class Student{ int rollno; String name; void insertRecord(int r, String n){ rollno=r; name=n; } void displayInformation(){System.out.println(rollno+" "+name);} } class TestStudent4{ public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); s1.insertRecord(111,"Karan"); s2.insertRecord(222,"Aryan"); s1.displayInformation(); s2.displayInformation(); } }
As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory.
We will learn about constructors in Java later.
Let's see an example where we are maintaining records of employees.
File: TestEmployee.java
class Employee{ int id; String name; float salary; void insert(int i, String n, float s) { id=i; name=n; salary=s; } void display(){System.out.println(id+" "+name+" "+salary);} } public class TestEmployee { public static void main(String[] args) { Employee e1=new Employee(); Employee e2=new Employee(); Employee e3=new Employee(); e1.insert(101,"ajeet",45000); e2.insert(102,"irfan",25000); e3.insert(103,"nakul",55000); e1.display(); e2.display(); e3.display(); } }
There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
class Rectangle{ int length; int width; void insert(int l, int w){ length=l; width=w; } void calculateArea(){System.out.println(length*width);} } class TestRectangle1{ public static void main(String args[]){ Rectangle r1=new Rectangle(); Rectangle r2=new Rectangle(); r1.insert(11,5); r2.insert(3,15); r1.calculateArea(); r2.calculateArea(); } }
There are many ways to create an object in java. They are:
We will learn these ways to create object later.
Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only.
If you have to use an object only once, an anonymous object is a good approach. For example:
new Calculation();//anonymous object
Calculation c=new Calculation(); c.fact(5);
Calling method through an anonymous object
new Calculation().fact(5);
Let's see the full example of an anonymous object in Java.
class Calculation{ void fact(int n){ int fact=1; for(int i=1;i<=n;i++){ fact=fact*i; } System.out.println("factorial is "+fact); } public static void main(String args[]){ new Calculation().fact(5);//calling method with anonymous object } }
We can create multiple objects by one type only as we do in case of primitives.
Initialization of primitive variables:
int a=10, b=20;
Initialization of reference variables:
Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects
Let's see the example:
//Java Program to illustrate the use of Rectangle class which //has length and width data members class Rectangle{ int length; int width; void insert(int l,int w){ length=l; width=w; } void calculateArea(){System.out.println(length*width);} } class TestRectangle2{ public static void main(String args[]){ Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects r1.insert(11,5); r2.insert(3,15); r1.calculateArea(); r2.calculateArea(); } }
File: TestAccount.java
//Java Program to demonstrate the working of a banking-system //where we deposit and withdraw amount from our account. //Creating an Account class which has deposit() and withdraw() methods class Account{ int acc_no; String name; float amount; //Method to initialize object void insert(int a,String n,float amt){ acc_no=a; name=n; amount=amt; } //deposit method void deposit(float amt){ amount=amount+amt; System.out.println(amt+" deposited"); } //withdraw method void withdraw(float amt){ if(amount