# 4) Object and class

### **Object and class in Java**

**Class:** A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports. A class is a group of objects that has common properties.

“A class is a way of binding the data and associated methods in a single unit”

A class in java contains:

* Data Members
* Method
* Constructor
* Block
* Class and Interface

**Object:**&#x20;

* **Object** is the physical as well as logical entity whereas **class** is the only logical entity.
* Object is an instance of class, object has state and behaviors.&#x20;

**Note**: Instance is a mechanism of allocating sufficient amount of memory space for data members of a class.

**Example**: A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance.

An Object in java has three characteristics:

* State
* Behavior
* Identity

**State:** Represents data (value) of an object.

**Behavior:** Represents the behavior (functionality) of an object such as deposit, withdraw etc.

**Identity:** Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely.

You can get the unique id of an ID using following method.

```java
System.identityHashCode(obj);
```

Class is also can be used to achieve user defined data types.

**Example 1**

Animal Class:

Dog, cat, and cow are belong to animal's class.&#x20;

Each object has state and behaviors.&#x20;

State: - color, name, height, age etc.

Behaviors: - barking, eating, and sleeping etc.

**Example 2**

A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class.

**Syntax to declare a Class**

class Class\_Name

&#x20; { &#x20;

&#x20;   data member; &#x20;

&#x20;   method; &#x20;

&#x20; }&#x20;

### **Steps for compiling and executing the java program**

Java is very simple programming language first we write a java program and save it with program class name.

In below program we create a java program with "Test" name so we save this program with "Test.java" file name. We can save our java program anywhere in our system or computer.

**Example 1:**

```java
class Test {
	public static void main(String[] args) {
		System.out.println("Hello World");
		System.out.println("This is My First Java Program");
	}
}
```

**Save Java Program**

Syntax: Filename.java

Example: Test.java

**Compile and Execute Java Code**

To compile:  javac Test.java

To execute:  java Test

**Output**

Hello World&#x20;

This is My First Java Program

**Note:** Here **Javac** and **Java** are called tools or application programs or exe files developed by sun micro system and supply as a part of jdk 1.6/1.7/1.8 in bin folder. **Javac** is used for compile the java program and **java** is used for run the java program.

**Note:** A java program can contain any number of main method but JVM start execution from that main() method which is taking array of object of String class.

### **Run in IDE:**

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LaihBy5VF14CWgY6Mbu%2F-LailQUGTO-frY1TEN4c%2FScreen%20Shot%202019-03-24%20at%201.46.17%20PM.png?alt=media\&token=543cd805-5ac9-4f79-b389-91494ab8c46c)

#### Output :

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LaihBy5VF14CWgY6Mbu%2F-LailaUmfPiQGCWcdwBQ%2FScreen%20Shot%202019-03-24%20at%201.47.00%20PM.png?alt=media\&token=f637ed09-f68e-493e-af9a-399c3c2c0949)

### **Java Execution :**

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTGaWNddvOALKtIqdOT%2F-LTGb0DFxKP7-g3kZ5yk%2FScreen%20Shot%202018-12-09%20at%2011.46.01%20AM.png?alt=media\&token=5669793a-084b-4510-ad88-593a484a1f8a)

\
Java bytecode is the end product which is executed by JVM.

What if my java source code contains more than class definitions and all are to be executed ?

An executable Java class, when handed over to the JVM, starts its execution at a particular point in the class—the main method. The JVM starts executing the code that’s defined in the main method. You can’t hand over a non-executable Java class (class without a main method) to the JVM and ask it to execute it. In this case, the JVM won’t know which method to execute because no entry point is marked.

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTGaWNddvOALKtIqdOT%2F-LTGc1nPgSHvKUSVI1t-%2FScreen%20Shot%202018-12-09%20at%2011.50.38%20AM.png?alt=media\&token=e5a8e955-b3b3-48e8-978f-dd7fc0e2c1e8)

#### Main Method:

The first requirement in creating an executable Java application is to create a class with a method whose signature (name and method arguments) matches the main method, defined as follows:

```java
public class HelloExam {
            public static void main(String args[]) {
               System.out.println("Hello exam");
            }
}
```

This main method should comply with the following rules:

* The method must be marked as a public method.
* The method must be marked as a static method.
* The name of the method must be main.
* The return type of this method must be void.
* The method must accept a method argument of a String array or a variable argument (varargs) of type String.

![](https://3494582050-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LSemf7mp1liQa7nfIAC%2F-LTGaWNddvOALKtIqdOT%2F-LTGcXYhF5LvVwBfIEnL%2FScreen%20Shot%202018-12-09%20at%2011.52.47%20AM.png?alt=media\&token=44f75514-3cfb-44f0-a949-799e24740ebe)

#### Guess the Output:

{% tabs %}
{% tab title="Program" %}

```java
public class HelloExam {
public static void main(String args) {
        System.out.println("Hello exam 2");
}
public static void main(String args[]) {
        System.out.println("Hello exam");
}
public static void main(int number) {
        System.out.println("Hello exam 3");
    }
}
```

{% endtab %}
{% endtabs %}

**Example of Object and Class**

In this example, we have created an Employee class that has two data members, eid and ename. We are creating the object of the Employee class by new keyword and printing the objects value.

**Example 2**

```java
package com.gs.ilp.corejava.objectAndClass.basics;

public class Employee {
	int eid = 852; // data member (or instance variable)
	String ename = "Rohit"; // data member (or instance variable)

	public static void main(String args[]) {
		Employee e = new Employee(); // Creating an object of class Employee
		System.out.println("Employee ID: " + e.eid);
		System.out.println("Name: " + e.ename);
	}
}
```

**Output**

Employee ID: 852

Name: Rohit

**NOTE:**

• JAVA always follows dynamic memory allocation but not static memory allocation.

• In order to create a memory space in JAVA we must use an operator called new. This new operator is known as dynamic memory allocation operator.

**Syntax 1 for defining an OBJECT:**

**\<Clsname> objname = new \<clsname ()>**

**Clsname** represents name of the class. **Objname** represents JAVA valid variable name treated as object. **New** is called dynamic memory allocation operator.

**Clsname** () represents constructor. The new operator will perform two standard actions.

They are:

* 1. It allocates sufficient amount of memory space for the data members of the class.
  2. It takes an address of the class and stored in the left hand side variable of syntax 1

**Syntax 2 for defining an OBJECT:**

**\<Clsname> objname; //object declaration**

**Objname = new \<clsname ()>; //object refrencing**

**Example 3:**

```java
package com.gs.ilp.corejava.objectAndClass.basics;

public class Emp {
	int eid = 1020;
	String eName = "Mohit";

	void show() {
		System.out.println("eid=" + eid);
		System.out.println("eName=" + eName);
	}

	public static void main(String[] args) {
		Emp obj = new Emp();
		Emp obj2 = new Emp();
		obj.show();
		obj2.show();
	}
}
```

**Output:**

eid=1020

eName=**Mohit**

eid=1020

eName=Mohit

**Example: 4**

```java
package com.gs.ilp.corejava.objectAndClass.basics;

public class Empoloyeee {
	int eid;
	String eName;

	void setValue(int a, String b) {
		eid = a;
		eName = b;
	}

	void show() {
		System.out.println("eid=" + eid);
		System.out.println("eName=" + eName);
	}

	public static void main(String[] args) {
		Empoloyeee obj1 = new Empoloyeee();
		Empoloyeee obj2 = new Empoloyeee();
		obj1.setValue(747, "Mohit");
		obj2.setValue(856, "Rohit");
		obj1.show();
		obj2.show();
	}
}
```

**Output:**

eid=747

eName=**Mohit**

eid=856

eName=Rohit

**Difference between Class and Object**

|   | **Class**                                                       | **Object**                                                                                           |
| - | --------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| 1 | Class is a container which collection of variables and methods. | object is an instance of class                                                                       |
| 2 | No memory is allocated at the time of declaration               | Sufficient memory space will be allocated for all the variables of class at the time of declaration. |
| 3 | One class definition should exist only once in the program.     | For one class multiple objects can be created.                                                       |


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gyansetu-java.gitbook.io/core-java/4-object-and-class.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
