
CLASS
Java is a true object oriented programming language and therefore a underline structure of all Java programs is class. Anything we wish to represent in a Java programs must be encapsulated in a class. That defines the state of behaviour of a basic program components known as object class create object and object use method to communicate between them that is all object oriented programming language.
A class is essentially a description of how to make an object that contains fields and methods.
Defining a class- A class is user defined Data type with a template to that surve to define it's properties. Once a class type has been defined, we can create variable of that type. The basic form of a class defination is-
class classname[superclass]
{
[Fields Description;]
[method description;]
}
Fields Description- Data is encapsulated in a class by placing Data fields inside the body of the class defination. These variables are called instance variable because they are created whenever an object of class is instantiated. we can declared the instance variable exactly the same way as declare local variables.
For example-
class Rectangle
{
int length;
int width;
}
Method Declaration- A class with in only Data fields has no life. The object created by such a class can not respond to any message. We must therefore add method that are necessary for manipulating the Data contained in the class. Methods are Declared inside the body of the class but immediately after the declaration of instance variables.
The General form of a method declaration is-
Type. method name (parameters list)
{
method body;
}
Method Declaration have four basic parts-
1- The name of the methods
2- The type of the value the method returns.(type).
3- A list of parameters.
4- The body of the methods.
The type specifies the type of the value , the method would return. This could be void type.
Example-
class Rectangle
{
int length;
int width;
void getdata(int x, int y)
{
length=x;
width=y;
}
}
Creating objects- An object in java is essentially a block of memory that contains space to store all instance variable. creating an object is also refered to as instantiating an object.
objects in java are created using the new operator . the new operator creates an object of the specified class and return a reference to that object.
Rectangle rect1= new Rectangle ();
Accessing class member- all variable must be assigned vales before they are used since we are outside the class, we can't access the instance variable and methods directly to do this we must use the object and (.) Dot operator as given below-
Object Name.variable name=value;
object Name.methodname(parameters);
No comments:
Post a Comment