Defining a class
A class is a user-defined data type or group of object with a template or blueprint that serves to define its properties. It is a logical entity. Once a class type has been define, we can create "Variables" which are similar to basic type declaration. In java, variables are termed as instance of class, which actual object. The basic form class defination is as follows:
class classname [extends superclassname]{
[fields declaration]
[method declaration]
}
The classname and superclassname are valid java identifiers. The keyword extends indicate that superclassname properties extended into classname. It is a pert of inheritance. (We will discuss inheritance in later part.) Everything inside square brackets is optional that means we can use as per the requirements. For example,
class Empty{
}
In above example, the Empty class is class name. This class does not have any properties and therefor cannot do anything.
A java class content:
- Field or Fields declaration
- Methods declaration
- Constructor
- Block
Field OR Fields declaration:
Data is encapsulated in a class by placing fields inside the body of class defination. These variables called instance variables because they are created whenever object of the class instantiated. We declare instance variable exactly same way we declare local variables. For example,
class Rectangle{
int length;
int width;
}
The class Rectangle have two integer type instance variables. It also allows to declare them in line like,
int length, width;
Remember these variables are only declare and therefor no storage space has been created in memory for them.
Methods declaration:
A class with only data fields has no life. The objects created by such a class cannot respond any message. We must add method which is nessasary to manipulate the data contained in class. Methods are declare insode body of the class but immediately after the declareation of instance variables. The general form of method declaration is as follows:
type methodname(parameter list){
method-body;
}
Method has four basic parts:
- The name of method (methodname)
- Type of the value method returns (type).
- A list of parameters (parameter list)
- The body of method.
- Default Constructors.
- Parameterised constructors.
222 Aryan
Comments
Post a Comment