In
this tutorial, we will learn about Java objects. In object-oriented
programming language, we design a program using objects and classes.
- A java object is a combination of data/information and procedures working on the available data.
- An object is an interface of a class.
- An object is a real-world entity.
- An object is a run-time entity.
- The object is an entity, which has state and behavior.
Example:
Pen,
Pencil, Apple, Laptop, Laptop bag, Chair, Table, Bike, Car, etc.
It
can be physical/logical.
Characteristics
of Object
An
object has three characteristics:
- State: Represents the data of an object.
- Behavior: Represents the behavior of an object, such as deposit, withdraw, etc.
- Identity: It is used internally by the JVM to identify each object uniquely.
new keyword in Java
The
new keyword is used to allocate memory at runtime. All objects get
memory in Heap memory area.
How
to Create a New Object in Java
There
are two ways to create objects in java:
1.
class_name
object_name = new class_name();
2. object_name
= new class_name(); //anonymous or nameless objects
Example:
Demo
program to create objects in java.
public
class ObjectDemo1{
int
num1 = 100;
int
num2 = 200;
static
int num3 = 300;
static
int num4 = 400;
//creating
main or static method
public
static void main (String[] args){
//main
or static area
//creating
new object
//ObjectDemo1
obj = new ObjectDemo1();
obj
= new ObjectDemo1(); //anonymous or nameless object
//calling
instance variables
System.out.println
(obj.num1);
System.out.println
(obj.num2);
//calling
static variables
//System.out.println
(obj.num3);
//System.out.println
(obj.num4); //not recommended
//static
variables – direct access
//System.out.println
(num3);
//System.out.println
(num4); //not recommended
//calling
static variables using class name
System.out.println
(ObjectDemo1.num3);
System.out.println
(ObjectDemo1.num4); //recommended
}
}
Save
this file as 'ObjectDemo1.java'
Compile:
$javac ObjectDemo1.java
Execute:
$java ObjectDemo1
Output:
100
200
300
400
0 Comments