Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Class:
A class is a user defined data types that provides convenient method for
packing together a group of logically related data items and functions
that work on them. In Java, the data items are called fields and functions
are called as methods. A class is a template that serves to define its
properties. Once the class type has been defined, we can create variables
of such type known as instances of classes.
Defining a class:
class ClassName
{
[Fields declaration]
[Method declaration]
}
In the above the class keyword tells that the following ClassName is an
user defined data type.
Fields Declaration:
Data is encapsulated into the class by placing data fields inside the body
of the class definition. These variables are called as Instance Variables
because they are created every time an object of class has been
instantiated.
Example:
class Rectangle
{
int len;
int eid;
}
Method Declaration:
A class with only data fields has no life. We must include code to operate
on the data contained in the class using methods.
Method declaration:
ret_type methodname ( parameter-list )
{
---------------------------------------------------------Method-body;
}
Method declaration has four basic parts.
The type of the value that the method returns (ret_type)
The name of the method (methodname).
A list of parameters (parameter-list), means the number and
type of values that received by the method.
The body of the method that contains a set of statements to
implement the task.
Example:
class Rectangle
{
int len;
int wid;
void getData(int x,int y)
{
len = x;
wid = y;
}
void rectArea()
{
int area = len * wid;
r1 = new Rectangle();
Action
Statement
Result
Declare
Rectangle r1;
null
Instantiate
r1 = new Rectangle();
r1
r1
Rectangle Object
Both statements can be combined as
Rectangle r1 = new Rectangle();
Note: Each object of a class has its own copy of the instance
variables. This means that any changes to the variables of one object will
not effect on the variables of another.
Accessing Class Members: