Object & Classes in Java
In this blog post, we will learn about the basic building blocks of any object-oriented programming language.
1-Classes
2-Objects
3-fields
4-methods
5-constructors
Class:
A class can be defined as a template/blueprint that describes the behaviors/states that the object and its type of support. A class has a certain set of properties.
A class can have
1-Data members
2-Methods
3-Blocks
4-Constructor
5-Class and Interface
Object:
An object is a real-world entity it can be physical as well as logical. An object is also known as an instance of a class. An object has a certain state and behaviors.
An object has three important characteristics:
1-Identity
2-State
3-Behaviors
1-Identity: Each Object identity is typically implemented via a unique ID by JVM. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object.
2-State: Represents data(value) of an object.
3-Behaviors: Represents the functionality(behavior) of an object.
Below is the real-world example of Class and object.
Car, bike, truck these all belong to vehicle class. Objects have also different states and behaviors. For example, the car has states like – color, name, model, speed, Mileage and as well as behaviors - distance travel.
In java class is defined by keyword “class” an object is created by a “new” keyword.
Demo Example:
class vehicle{
String name;
String color;
String model;
int speed;
public void distance ()
{
// Functions are defined here
}
}
Object Creation in java
The below example shows how to create object in java
class A{
public static void main(String [] args)
{
// creating vechile object
vehicle obj=new vehicle();
// Access the data members of vechile class
obj.name;
obj.distance(); // Access the method of vechile class
}
}