A class is a blue print
to create an object.
Let us try to understand
this by an example:
Let us say, we have a
feedback form which needs to be filled by all the workers regarding a feedback
of a product or application of their organization.
The feedback form may
contain the below details
Now the admin have the
original form (master copy) from which he/she took the other 100 photo copies
and also the 100 forms which are filled by the workers.
If we relate this
example with Java, we can term the master copy(blue print) as a Class.
The other 100 forms
which are replicated from the master copy are called as objects.
The name, id or any
field will not be filled in the master copy so as to use that to take more
photo copies in future. So, the master copy won’t be bearing any value to
itself. But the photo copies that were taken and filled by the workers have
values assigned to them.(name, id, address, feedback of diff workers)
In the same way in Java,
a class is a blue print from which the objects can be created and each object
have its own value.
If we want to create
1000 employees in java, we create an Employee class and then create 1000
employee objects and each object will have its own value. The object just uses
the blue print/structure of the class.
As the Name, id and
other fields in the form differ from employee to employee, they are called as
variables in java.
Let us say, we need the
company name to be printed on the form. Instead of asking the workers to fill
the company name, the master copy can be edited such that it has the company
name. So, once the photo copies are taken, all the copies will have the same
value.
As we want this value to
be same across multiple objects, we made the change at the class level and so
these variables (like company name) are called as class variables.
The way the admin
created the form, let us try to create a class in Java which represents the
feedback form.
Class name can be
‘FeedBackForm’
-
As Name,
Address, Feedback are alphanumeric, they should be String variables
in Java
-
As ID
is numeric field, it should be a Int variable in Java
-
A class is
defined in a curly brace with the key word class.
The class of the
FeedbackForm can be :
And this should be saved
in a file with the name FeedBackForm.java (should be the name of the public
class)
Now, as the admin of the
organization took photo copies of the master copy and made objects, we will see
how to do that photo copy in java.
We create a copy of the
class by the following command.
FeedBackForm f1 = new
FeedBackForm();
Where FeedBackForm is
the name of the class, f1 is the name of the object.If we want to create 100
objects:
The FeedBackForm() you
see in the object creation is called as constructor. A constructor is used to
create a object in Java. We will know more about the constructors in other
sections.