Object in Java
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 in Java
is the physical as well as a logical entity, whereas, a class in
oject in java |
An object has three characteristics:
- State: represents
the data (value) of an object.
- Behavior: represents
the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely.
object in java |
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:
- An object is a real-world entity.
- An object is a runtime entity.
- The object is an entity which has state and behavior.
- The object is an instance of a class.
Example of Object:
object in java exemple |
Objects correspond to
things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might
have objects such as “shopping cart”, “customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated. All the instances share the attributes
and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of
instances
Example:
object in java example |
Initializing an object
The new operator instantiates a class by
allocating memory for a new object and returning a reference to that memory.
The new operator also invokes the class constructor.
//
Class Declaration
public
class Dog
{
//
Instance Variables
String
name;
String
breed;
int
age;
String
color;
//
Constructor Declaration of Class
public
Dog(String name, String breed,
int
age, String color)
{
this.name
= name;
this.breed
= breed;
this.age
= age;
this.color
= color;
}
//
method 1
public
String getName()
{
return
name;
}
//
method 2
public
String getBreed()
{
return
breed;
}
//
method 3
public
int getAge()
{
return
age;
}
//
method 4
public
String getColor()
{
return
color;
}
@Override
public
String toString()
{
return("Hi
my name is "+ this.getName()+
".\nMy
breed,age and color are " +
this.getBreed()+","
+ this.getAge()+
","+
this.getColor());
}
public
static void main(String[] args)
{
Dog
tuffy = new Dog("tuffy","papillon", 5,
"white");
System.out.println(tuffy.toString());
}
}
|
Output:
Hi my name is tuffy.
My breed,age and color are papillon,5,white
No comments:
Post a Comment