Monday 30 January 2012

Classes and Objects

Class:
•A class is collection of similar objects or a class is a blueprint for all the objects.
•Based on the blueprint(class) all the objects are built.
•A class specifies the common behavior for all its objects.
•By creating a class we are creating a user-defined data type.
•A class is a logical construct. It does not occupy any memory.

Example: People is a class.
Ram, shyam, rahul etc are objects of the class “People”.

Declaring a Class:
•In Java a class is declared using the keyword “class”.
Syntax for declaring a class is as follows:

class ClassName
{
    member(s);
}

Class naming convention:
•In Java class names follow a certain convention. If the class name consists of two words, every first letter in each word will be in uppercase and rest of the letters will be in lowercase.

Ex: ClassName, People, Animals, HelloWorld, Shape, NewShape etc…

Class Members:
•A class can contain variables, methods and other things.
•Variables in a class are also called as fields.
•Variables declared within a class and outside the methods and which are non-static are called “instance variables” and which are declared as static are called “class variables”.
•Instance variables got there name as all objects of the class will be containing a copy of each instance variable.

Objects:
•Everything around us can be viewed as an object. Ex: bat, ball, duster, chalk, book etc..
•An object is defined as a self defined entity.
•An object has two things, state and behavior.
•State represents the characteristics of the object where as behavior represents “what we can do to the object or what the object does for us”.
•In programming state is represented as a set of variables and behavior is represented as a set of methods.
•Object is a realization. It occupies memory in the RAM.



•Syntax for declaring the objects is as follows:
ClassName object-identifier = new ClassName();

•Here object-identifier can be any valid identifier.
•“new” keyword in java is used to allocate memory for the object dynamically (at run-time).
•In the above syntax, object-identifier is just a reference which refers to the actual object created in memory using the “new” keyword.


Accessing Members:
•Members of a class are always accessed using the object of that class.

Syntax: object-name.member;

Example:
class Box
{
    int length, width, height;
    void area()
    { System.out.println(“Area of Box”); }
}
class BoxDemo
{
   Box b = new Box();
   b.length = 10;
   b.area();
}

No comments:

Post a Comment