Friday 27 May 2016

Object & Classes in Java

In this blog post,we will learn about 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/blue print that describes the behaviors/states that the object and its type support.A class have 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 instance of a class.An object have certain state and behaviors.

An object have 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 are belongs to vehicle class.The Objects have also different different states and behaviors.For example car has states like - color, name, model, speed, Mileage and as well as behaviors - distance travel.
In java class is defined by keyword "class" and object is created by "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

}

}

No comments:

Post a Comment