Class :
Class
is the blue print of the real objects to be created. The class gives the
skeleton for an entity to be created for real time processing. Class is a
software template that defines the methods and variables to be included in a
particular kind of Object.
A
class may contain member variables, methods, constructors and static blocks
which can be used to define and manupulate state and behavious of an object.
Object :
The
java is all about objects. An Object is the real entity in the world. Every
object will have its state and behavior. Concept of Object can be easily
understood taking any really time entity around us say Dog, television, Fridge
or car etc. A car may have states like
number of wheels, type of engine etc and behvior like way of start, speedup
etc.
Below is the syntax for the class.
Access specifier Class ClassName
{
Member
variables --- defines state of an object
Methods
--- defines the behaviour of the object
}
Object declaration will be like below:
ClassName object = new ClassName()
Example:
We
can define a class Vehicle to have an skeleton for all types of vehicles by
preparing set of properties and type of processes required to use those
vehicle. After that we can create real time object such as car, truck or tempo
depending upon the states(properties).
Declaring a class : Vehicle
public class Vehicle
{
//member
variables which will define the state of a vehicle
private int wheels;
private
String sengineType;
//setter
method to set number of wheels
public void setWheels(int
wheels)
{
this.wheels
= wheels;
}
//getter method to retrieve the
number of wheels
public int getWheels()
{
return
this.wheels;
}
}
See below, how will we use this class to instantiate any
real object.
public class Demo
{
//main
method
Public
static void main(String args[])
{
//calling
default constructor to create an object.
Vehicle car =
new Vehicle();
Vehicle tempo =
new Vehicle();
//calling
setter method to set the states of the car object
car.setWheels(4);
tempo.setWheels(3);
//calling
getter method to access the object states
System.out.println(“
Car : No. of wheels :”+car.getWheels());
System.out.println(“
Tempo : No. of wheels :”+tempo.getWheels());
}
}
.
No comments:
Post a Comment