Object and Class in Java
Navatha Kannadi
Business Architect| Lead Business Analyst at Capgemini Engineering | Law Student - Certified in Leading safe 6.0, Safe PM/PO, PSM 1
Let’s discuss the core thing on which we been and going to write the Java Programs. Those are OBJECT and CLASS.
Object defines the state, behavior and identity of a subsistence technically known as entity.
- 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.
Take a real life example: let’s take a Pen and relate the same with above, pen is an object with some name say “Parker”, it has some color say “Red” these properties are termed as “State”, the pen is used for “writing” so writing is the “Behavior” and the pen will be having a cap, refill, nib etc. can be called the Identity.
A class is a group of objects that has common properties. It is a template or blueprint from which objects are created.
A class in java can contain:
- data member
- method
- constructor
- block
- class and interface
Syntax to declare a class:
class <class_name> {
data member;
method;
}
Instance variable in Java
A variable that is created inside the class but outside the method is known as instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when object (instance) is created. That is why, it is known as instance variable.
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
- Code Reusability
- Code Optimization
- new keyword
The new keyword is used to allocate memory at runtime.
Cheers :) Navatha