Java : Object and Class

Objects and Classes in Java

In object-oriented programming, objects and classes are fundamental components. They represent the two main pillars of OOP, and it's impossible to create a program in Java without them. In this section, we'll explore the concepts of objects and classes in Java.


What is an object in Java?

object in Java

An object is a real-world entity characterized by its state and behavior. In simpler terms, it's something tangible that you can touch and feel, such as a car or a chair. For example, the banking system represents an intangible object. Each object possesses a unique identity, typically represented by a unique ID that the JVM uses internally for identification purposes.


Characteristics of an Object


State: This refers to the data or values held by an object.

Behavior: This defines the functionality of an object, such as actions like depositing or withdrawing.

Identity: An object's identity is generally represented by a unique ID. While this ID is not visible to users, it is crucial for the JVM to distinguish each object uniquely.

Example of an Object in Java

Consider a pen as an object. Its state includes attributes like its name (Reynolds) and color (white). Its behavior is its functional capability, such as writing.

An object is an instance of a class, which acts as a template or blueprint for creating objects. In simpler terms, an object is the result of instantiating a class.

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
  1. An object is a real-world entity.
  2. An object is a runtime entity.
  3. An object is an entity that has state and behavior.
  4. An object is an instance of a class.

What is a Class in Java?

A class is a collection of objects that share common properties. It serves as a template or blueprint from which objects are created. Unlike objects, a class is a logical entity and does not have a physical presence.


A class in Java can contain

:Class in Java

1. Fields

Fields are variables declared within a class that represent the state of the objects created from that class. Also known as instance variables, they define the data stored in each object. Access modifiers like public, private, and protected can be applied to fields to control their visibility and accessibility.

2. Methods

Methods are functions defined within a class that describe the actions or behaviors that objects of that class can perform. They enable interaction with and modification of an object's state (its fields). Methods can either be void (returning nothing) or return values, and they can also have different access modifiers.


3. Constructors

Constructors are special methods used to initialize class objects. When an object is created using the new keyword, the constructor is invoked and shares the same name as the class. Constructors can initialize an object's fields and perform any necessary setup during object creation.

4. Blocks

Java supports two types of blocks within a class: instance blocks (also known as initialization blocks) and static blocks. Static blocks are executed only once when the class is loaded into memory, typically for static initialization. Instance blocks, on the other hand, are executed each time a new object of the class is created and can be used to initialize instance variables.

5. Nested Class and Interface

Java allows classes and interfaces to be nested within other classes and interfaces. Nested classes can be either static or non-static and have access to the members (fields and methods) of the enclosing class. Nested interfaces, which are implicitly static, can be used to group related constants and methods logically.

Syntax of a Class

  1. class <class_name>{  
  2.     field;  
  3.     method;  
  4. }  

Instance Variable in Java


An instance variable is a variable defined within a class but outside any method. Unlike local variables, instance variables do not receive memory allocation at compile time; instead, they are allocated memory at runtime when an object (or instance) is created.

Each instance of a class has its own copy of the instance variables, meaning that changes to the instance variables of one object do not affect those of other objects of the same class. Instance variables can be initialized using constructors or setter methods. They are essential in object-oriented programming, as they encapsulate data within objects and often represent the state or properties of those objects.

Method in Java

In Java, a method is a block of code defined within a class that performs a specific function. Methods provide a way to interact with an object's state and encapsulate behavior within objects.

Advantages of Methods

Code Reusability: Methods promote code reusability by allowing the same block of code to be executed multiple times throughout a program. Once defined, a method can be called from anywhere within its scope.

Code Optimization: Methods help optimize code by encapsulating complex or repetitive tasks into reusable components. This modularization enhances readability and simplifies maintenance.

The new Keyword in Java

The new keyword is used to allocate memory at runtime. All objects are allocated memory in the heap memory area.

In Java, an instance of a class—commonly referred to as an object—is created using the new keyword. This keyword dynamically allocates memory for the object and returns a reference to it when followed by the class name and parentheses, which may include optional arguments.

MyClass.java

  1. public class MyClass {  
  2.     int myField;  
  3.     public MyClass(int value) {  
  4.         myField = value;  
  5.     }  
  6.     public static void main(String[] args) {  
  7.         // Using the new keyword to create an instance of MyClass  
  8.         MyClass myObject = new MyClass(10);  
  9.         // Accessing the instance variable of the object  
  10.         System.out.println("Value of myField: " + myObject.myField);  
  11.     }  
  12. }  

Output:

Value of myField: 10 

Explanation

In this example, the constructor MyClass(int value) is called with the parameter 10, the reference to the newly constructed object is assigned to the variable myObject, and new MyClass(10) dynamically allocates memory for an object of type MyClass. Lastly, a printout of the instance variable myField's value is obtained.

Object and Class Example: main within the class

In Java, the main() method can be declared in a class, which is typically done in demonstration or basic programs. Having the main() method defined inside of a class allows a program to run immediately without creating a separate class containing it.

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

  1. //Java Program to illustrate how to define a class and fields  
  2. //Defining a Student class.  
  3. class Student{  
  4.  //defining fields  
  5.  int id;//field or data member or instance variable  
  6.  String name;  
  7.  //creating main method inside the Student class  
  8.  public static void main(String args[]){  
  9.   //Creating an object or instance  
  10.   Student s1=new Student();//creating an object of Student  
  11.   //Printing values of the object  
  12.   System.out.println(s1.id);//accessing member through reference variable  
  13.   System.out.println(s1.name);  
  14.  }  
  15. }  

Output:

0
null

Explanation

In this example, the constructor MyClass(int value) is invoked with the parameter 10, resulting in a new MyClass object being created and its reference assigned to the variable myObject. The new MyClass(10) statement dynamically allocates memory for this object. Finally, the value of the instance variable myField is printed.

Object and Class Example: main Method Within a Class

In Java, the main() method can be defined within a class, which is common for demonstrations or simple programs. This allows the program to run immediately without needing a separate class for execution.

In the following example, a Student class is created with two data members: id and name. We instantiate the Student class using the new keyword and print the object's values. The main() method is included within the class to facilitate running the program.

File: TestStudent1.java

  1. //Java Program to demonstrate having the main method in   
  2. //another class  
  3. //Creating Student class.  
  4. class Student{  
  5.  int id;  
  6.  String name;  
  7. }  
  8. //Creating another class TestStudent1 which contains the main method  
  9. class TestStudent1{  
  10.  public static void main(String args[]){  
  11.   Student s1=new Student();  
  12.   System.out.println(s1.id);  
  13.   System.out.println(s1.name);  
  14.  }  
  15. }  

Output:

0
null 

Explanation

In this Java program, the main method is located in a different class than the Student class. The Student class does not define any methods for its fields, name and id. The main method exists in another class called TestStudent1, where it uses the default constructor to create an object s1 of type Student. Because the fields name and id are not explicitly initialized, they have default values: null for the String and 0 for the int.

Object Initialization in Java

There are three main ways to initialize an object in Java:

  1. By Reference Variable
  2. By Method
  3. By Constructor

1) Initialization through Reference Variable

Initializing an object means assigning data to its fields. Below is a simple example demonstrating how to initialize an object through a reference variable.

File: TestStudent2.java

  1. class Student{  
  2.  int id;  
  3.  String name;  
  4. }  
  5. class TestStudent2{  
  6.  public static void main(String args[]){  
  7.   Student s1=new Student();  
  8.   s1.id=101;  
  9.   s1.name="Sonoo";  
  10.   System.out.println(s1.id+" "+s1.name);//printing members with a white space  
  11.  }  
  12. }  

Output:

101 Sonoo 


This Java code includes two classes: Student and TestStudent2. The Student class defines two fields, id and name, which represent the student's ID and name, respectively. The TestStudent2 class contains the main method, which serves as the entry point of the program. Inside this main method, an object s1 of type Student is created using the new keyword. The fields id and name of s1 are then initialized with the values 101 and "Sonoo".

Additionally, you can create multiple Student objects and store information in them using different reference variables.

File: TestStudent3.java

  1. class Student{  
  2.  int id;  
  3.  String name;  
  4. }  
  5. class TestStudent3{  
  6.  public static void main(String args[]){  
  7.   //Creating objects  
  8.   Student s1=new Student();  
  9.   Student s2=new Student();  
  10.   //Initializing objects  
  11.   s1.id=101;  
  12.   s1.name="Sonoo";  
  13.   s2.id=102;  
  14.   s2.name="Amit";  
  15.   //Printing data  
  16.   System.out.println(s1.id+" "+s1.name);  
  17.   System.out.println(s2.id+" "+s2.name);  
  18.  }  
  19. }  

Output:

101 Sonoo
102 Amit

Explanation

This Java code illustrates how to create and initialize multiple Student class objects within the TestStudent3 class. Using the new keyword, two Student objects, s1 and s2, are created. Each object's id and name fields are then initialized separately: s1 has an id of 101 and a name of "Sonoo," while s2 is assigned an id of 102 and a name of "Amit."

2) Initialization via Method

In this example, we create two Student objects and initialize their values by calling the insertRecord method.

We display the state (data) of the objects by invoking the displayInformation() method.
File: TestStudent4.java

  1. class Student{  
  2.  int rollno;  
  3.  String name;  
  4.  void insertRecord(int r, String n){  
  5.   rollno=r;  
  6.   name=n;  
  7.  }  
  8.  void displayInformation(){System.out.println(rollno+" "+name);}  
  9. }  
  10. class TestStudent4{  
  11.  public static void main(String args[]){  
  12.   Student s1=new Student();  
  13.   Student s2=new Student();  
  14.   s1.insertRecord(111,"Karan");  
  15.   s2.insertRecord(222,"Aryan");  
  16.   s1.displayInformation();  
  17.   s2.displayInformation();  
  18.  }  
  19. }  

Output:


11 Karan
222 Aryan
Explanation


The Java code provided defines two classes: Student and TestStudent4. The Student class contains fields for rollno and name, along with methods insertRecord and displayInformation to initialize and display the respective data. In the main method of the TestStudent4 class, two Student objects are created, and their insertRecord methods are called to set the values for rollno and name.

Object in Java with values



As illustrated in the figure above, objects are stored in the heap memory area, and reference variables point to these objects in memory. In this context, s1 and s2 are reference variables that reference the objects allocated in the heap.

3) Initialization Using a Constructor

Object initialization through a constructor is a fundamental concept in object-oriented programming in Java. Constructors are special methods within a class that are invoked when an object of that class is created using the new keyword. They set up the object's state by providing initial values for its fields or performing necessary setup tasks. The constructor is automatically called upon instantiating an object, ensuring that the object is properly initialized before it is used.

Here’s an example that demonstrates object initialization via a constructor:

File: ObjectConstructor.java

  1. class Student {  
  2.     int id;  
  3.     String name;  
  4.     // Constructor with parameters  
  5.     public Student(int id, String name) {  
  6.         this.id = id;  
  7.         this.name = name;  
  8.     }  
  9.     // Method to display student information  
  10.     public void displayInformation() {  
  11.         System.out.println("Student ID: " + id);  
  12.         System.out.println("Student Name: " + name);  
  13.     }  
  14. }  
  15. public class ObjectConstructor {  
  16.     public static void main(String[] args) {  
  17.         // Creating objects of Student class with constructor  
  18.         Student student1 = new Student(1"John Doe");  
  19.         Student student2 = new Student(2"Jane Smith");  
  20.         // Displaying information of the objects  
  21.         student1.displayInformation();  
  22.         student2.displayInformation();  
  23.     }  
  24. }  

Output:

Student ID: 1
Student Name: John Doe
Student ID: 2
Student Name: Jane Smith

Explanation

In this example, the id and name fields of a Student object are initialized through a constructor defined in the Student class, which takes two parameters: id and name. When creating the student1 and student2 objects using this constructor, their fields are set with the provided values. This approach ensures that objects are created with the correct initial values, making it simpler to instantiate and use them later in the program.

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

  1. class Employee{    
  2.     int id;    
  3.     String name;    
  4.     float salary;    
  5.     void insert(int i, String n, float s) {    
  6.         id=i;    
  7.         name=n;    
  8.         salary=s;    
  9.     }    
  10.     void display(){System.out.println(id+" "+name+" "+salary);}    
  11. }    
  12. public class TestEmployee {    
  13. public static void main(String[] args) {    
  14.     Employee e1=new Employee();    
  15.     Employee e2=new Employee();    
  16.     Employee e3=new Employee();    
  17.     e1.insert(101,"ajeet",45000);    
  18.     e2.insert(102,"irfan",25000);    
  19.     e3.insert(103,"nakul",55000);    
  20.     e1.display();    
  21.     e2.display();    
  22.     e3.display();    
  23. }    
  24. }    

Output:

101 ajeet 45000.0
102 irfan 25000.0
103 nakul 55000.0

Explanation


The Employee class in this Java code defines three fields: id, name, and salary. It includes two methods: insert, which sets the values of the fields, and display, which prints those values. In the main function of the TestEmployee class, three Employee objects (e1, e2, and e3) are created. The insert method is called for each object to initialize the id, name, and salary fields with specific values. Subsequently, the display method is invoked for each object to show the initialized data.

Object and Class Example: Rectangle


Another example is provided that handles the records for a Rectangle class.

File: TestRectangle1.java

  1. class Rectangle{  
  2.  int length;  
  3.  int width;  
  4.  void insert(int l, int w){  
  5.   length=l;  
  6.   width=w;  
  7.  }  
  8.  void calculateArea(){System.out.println(length*width);}  
  9. }  
  10. class TestRectangle1{  
  11.  public static void main(String args[]){  
  12.   Rectangle r1=new Rectangle();  
  13.   Rectangle r2=new Rectangle();  
  14.   r1.insert(11,5);  
  15.   r2.insert(3,15);  
  16.   r1.calculateArea();  
  17.   r2.calculateArea();  
  18. }  
  19. }  

Output:

55
45

Explanation

This Java code defines a Rectangle class with fields for length and width, along with methods to set the dimensions and calculate the area. In the main method of the TestRectangle1 class, two Rectangle objects are created, and their dimensions are set using the insert method.
Different Ways to Create an Object in Java

Using the new Keyword

The most common way to create an object in Java is with the new keyword followed by a constructor.
Example:java

ClassName obj = new ClassName();

This allocates memory for the object and calls its constructor to initialize it.

Using the newInstance() Method

This method, part of the java.lang.Class class, creates a new instance of a class dynamically at runtime, invoking the no-argument constructor.

Example:java


ClassName obj = (ClassName) Class.forName("ClassName").newInstance();

Using the clone() Method

The clone() method creates a copy of an existing object through a shallow copy, returning a new object that duplicates the original.

Example:java


ClassName obj2 = (ClassName) obj1.clone();

Using Deserialization

Objects can be created by deserializing them from a stream of bytes using the ObjectInputStream class. The object is read from a file or network, and the readObject() method is called to recreate it.

Using Factory Methods

Factory methods are static methods within a class that return instances of that class. They allow for encapsulating the object creation logic without directly invoking a constructor.

Example:java

ClassName obj = ClassName.createInstance();

These methods provide flexibility in how objects are instantiated in Java, catering to different needs and scenarios.

We will learn these ways to create object later.

Different Ways to create an Object in Java

    Anonymous Object

    An anonymous object is one that does not have a name or reference. It can only be used at the time of its creation.

Calling method through a reference:

  1. Calculation c=new Calculation();  
  2. c.fact(5);  

Calling method through an anonymous object

  1. new Calculation().fact(5);  

Let's see the full example of an anonymous object in Java.

  1. class Calculation{  
  2.  void fact(int  n){  
  3.   int fact=1;  
  4.   for(int i=1;i<=n;i++){  
  5.    fact=fact*i;  
  6.   }  
  7.  System.out.println("factorial is "+fact);  
  8. }  
  9. public static void main(String args[]){  
  10.  new Calculation().fact(5);//calling method with anonymous object  
  11. }  
  12. }  

Output:

Factorial is 120

Explanation

The factorial of an integer \( n \) can be calculated using Java code that defines a `Calculation` class with a `factorial` method. This method employs a for loop to compute the factorial by iterating from 1 to \( n \), and the result is then printed to the console. The main method demonstrates the use of an anonymous `Calculation` class object, which calls the `factorial` method with the parameter 5, showcasing how to use anonymous objects in Java for one-time method invocations.

Creating Multiple Objects of One Type

In Java, it's possible to create multiple objects of the same type, similar to how we handle primitive data types.

Initialization of Primitive Variables

  1. int a=10, b=20;  

Initialization of Reference Variables

  1. Rectangle r1=new Rectangle(), r2=new Rectangle();//creating two objects  

Let's see the example:

  1. //Java Program to illustrate the use of Rectangle class which  
  2. //has length and width data members  
  3. class Rectangle{  
  4.  int length;  
  5.  int width;  
  6.  void insert(int l,int w){  
  7.   length=l;  
  8.   width=w;  
  9.  }  
  10.  void calculateArea(){System.out.println(length*width);}  
  11. }  
  12. class TestRectangle2{  
  13.  public static void main(String args[]){  
  14.   Rectangle r1=new Rectangle(),r2=new Rectangle();//creating two objects  
  15.   r1.insert(11,5);  
  16.   r2.insert(3,15);  
  17.   r1.calculateArea();  
  18.   r2.calculateArea();  
  19. }  
  20. }  

Output:

55
45

Explanation

This Java program demonstrates the use of a Rectangle class, which has length and width as its data members. The class includes methods to insert dimensions and compute the area of a rectangle. In the main method of the TestRectangle2 class, two Rectangle objects (r1 and r2) are created in a single line using a comma-separated list, showcasing the ability to instantiate multiple objects of the same type at once. Each object's dimensions are set by calling the insert method, and the area of each rectangle is calculated and printed using the calculateArea method.

Real World Example: Account

File: TestAccount.java

  1. //Java Program to demonstrate the working of a banking-system  
  2. //where we deposit and withdraw amount from our account.  
  3. //Creating an Account class which has deposit() and withdraw() methods  
  4. class Account{  
  5. int acc_no;  
  6. String name;  
  7. float amount;  
  8. //Method to initialize object  
  9. void insert(int a,String n,float amt){  
  10. acc_no=a;  
  11. name=n;  
  12. amount=amt;  
  13. }  
  14. //deposit method  
  15. void deposit(float amt){  
  16. amount=amount+amt;  
  17. System.out.println(amt+" deposited");  
  18. }  
  19. //withdraw method  
  20. void withdraw(float amt){  
  21. if(amount<amt){  
  22. System.out.println("Insufficient Balance");  
  23. }else{  
  24. amount=amount-amt;  
  25. System.out.println(amt+" withdrawn");  
  26. }  
  27. }  
  28. //method to check the balance of the account  
  29. void checkBalance(){System.out.println("Balance is: "+amount);}  
  30. //method to display the values of an object  
  31. void display(){System.out.println(acc_no+" "+name+" "+amount);}  
  32. }  
  33. //Creating a test class to deposit and withdraw amount  
  34. class TestAccount{  
  35. public static void main(String[] args){  
  36. Account a1=new Account();  
  37. a1.insert(832345,"Ankit",1000);  
  38. a1.display();  
  39. a1.checkBalance();  
  40. a1.deposit(40000);  
  41. a1.checkBalance();  
  42. a1.withdraw(15000);  
  43. a1.checkBalance();  
  44. }}   

Output:

832345 Ankit 1000.0
Balance is: 1000.0
40000.0 deposited
Balance is: 41000.0
15000.0 withdrawn
Balance is: 26000.0

Explanation

The Account class in this Java program simulates a basic banking system with features for depositing, withdrawing, checking the balance, and viewing account details. It includes attributes such as account number, account holder's name, and balance amount. The main method of the TestAccount class is responsible for creating and initializing an Account object, a1, with the relevant information. Afterward, the account is utilized for deposits and withdrawals, and the balance is checked after each transaction.

একটি মন্তব্য পোস্ট করুন

নবীনতর পূর্বতন