Menus

Jul 23, 2016

Introduction to Java Class and Object

Course Contents:
  1. Form of class
  2. Objects declaration
  3. Methods
  4. Constructors
  5. This keyword
  6. Garbage collection


Class
A class is a user defined data type that is used to define its properties. A class consists of data member and member functions. The data or variables defined within a class are called instance variables because each instance of the class (that is each object of the class) contains its own copy of these variables.

The functions defined or declared within the class are known as methods. The method and variables defined within a class are called member of the class. In class the data for one object is separate and unique from the data for another.

The general syntax of class definition is:
Class classname
{
 Type instance_variable1;
 Type instance_variable2;
 ………;
 ……….;
 Type methodname(parameter list)
{
 //body of the method
}
Type methodname(parameter list)
{
 //body of method
}
 …………..
 Type method(parameter list)
 {
 //body of method
}
}


Here, in above example, class is a keyword and classname is any valid variable name. The body of the class is enclosed within the curly braces. Within the class we can add any number of instance variables and any number of methods.

Adding variables
Once a class is created, we can add any number of instance variables inside the class that is data can be encapsulated within the class. Instance variables can be declared exactly the same way as that of local variables.
Eg.
Class Rectangle
{
int length;
int width;
}
Adding methods
We can also add any number of methods inside the class to operate on the instance variables defined within that class. Methods are declared inside the body of the class but immediately after the declaration of instance variables. The general form of method declaration is:
 Type methodname (parameter list)
{
 Method body
}

Method declarations have four basic parts:
- The name of the method (methodname)
- The type of value the method returns (type)
- A list of parameters (parameter list)
- The body of the method
Eg.
Class Ractangle
{
 int length;
 int width;
 void getdata(int x , int y)
 {
 length = x;
 width = y;
}
}

In the above class, it consists of two data member length and width and one member function getdata that takes two arguments of type integer. This function is used to initializes the instance variable of the class Ractangle.
Creating object
An object in java is a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object.

Once the class has been created, we can create object of that type using new operator. The new operator dynamically allocates memory for an object and returns a reference to it. This ref erence is the address in
memory of the object allocated by new.
Syntax:
Classname objectname;// declare a class variable
Objectname = new classname();
The first statement declares a variable to hold the object reference and the second one actually assigns the object reference to the variable.
Eg.
Ractangle ract;
ract = new Ractangle();

The first line declares ract as reference to an object of type Rectangle. After this line executes, ract contains the value null, which indicates that it does not yet point to an actual object.

Any attempt to use ract at this point will result in a compile time error. The next line allocates an actual object and assigns a reference to it to ract. After the second line executes, we can use ract as Rectangle object. But in reality, ract simply holds the memor y address of the actual Rectangle object.

The new operator
The new operator dynamically allocates memor y for an object. The advantage of this approach is that program can create as many or as few objects as it needs during the execution of the program.

However, since memory is finite, it is possible that new will not be able to allocate memory for an object because of insufficient memory. If this happens, run-time exception will occurs. It has the following general form:
Class_variable = new classname();
Here, class variable is a variable of the class. The classname is the name of the class that is being instantiated. The class name followed by parenthesis specifies the constructor for the class.
A constructor defines what occurs when an object of a class is created.

Accessing class members
Data member and member function of the class can be accessed from outside the class using dot operator. The general syntax of member access is given below:

Objectname.variable name;
Objectname.methodname(parameter list);

Here objectname is the name of the object and variablename is the name of the instance variable inside the object that we wish to access, methodname is the method that we wish to call, and parameter-list is a comma separated list of actual values.
Eg.
ract.length=20;//accessing instance variable
ract.width=30;// /accessing instance variable
ract.getdata(2,5);//calling the member function

WAP that demonstrate the concept of class and object
class Rectangle
{
 int length;//variable declaration
 int width;
 void getdata(int x , int y)//definition of method
 {
 length = x;
 width = y;
 }
 int area()//definition of another method
 {
 int a;
 a= length*width;
 return(a);
 }
}

class RectArea
{
 public static void main(String args[])
 {
 Rectangle rect1 = new Rectangle();
 Rectangle rect2 = new Rectangle();
 int area1,area2;
 rect1.length=10;
 rect1.width=15;
 area1 = rect1.length * rect1.width;
 rect2.getdata(20,25);
 area2 = rect2.area();
 System.out.println("Area1=" + ar ea1);
 System.out.println("Area2 =" + area2);
}
}

Overloading methods
In java, it is possible to create methods that have the same name, but different parameter list and different definitions. This is called method overloading. Method overloading is used when objects are required to perform similar tasks but using different input parameters.

When we call the methods, Java matches up the method name first and then the number and type of parameters to decide which one of the definitions to execute. This process is known as polymorphism.

WAP that demonstrate the concept of method overloading
class OverloadDemo
{
 void test()
{
 System.out.println("No parameters");
}
void test(int a)
{
 System.out.println("a=" +a);
}
void test(int a , int b)
{
 System.out.println( "a and b: " +a + " " + b);
}
double test(double a)
{
 System.out.println("Double a = " +a);
 return (a*a);
}
}

class Overload
{
 public static void main(String args[])
 {
 OverloadDemo d = new OverloadDemo();
 double result;
 d.test();
 d.test(3);
 d.test(12,12);
 result = d.test(12.5);
 System.out.println("Result of d.test(12.5) is " + result);
}
}

Constructors
Constructors are the member functions (methods) that are used to initialize the instance variable of an object when the object of its class is created. It has same name as that of class and called automatically when the object is created. Constructors return nothing, so return type of constructor is nothing, not even void.
Syntax:
Classname(parameter_list)
{
 //body of constructor
}

Eg:
WAP that demonstrate the concept of constructor
class Rectangle
{
 int length,width;
 Rectangle()//non parameterized constructor definition
 {
 length=10;
 width=10;
}
 Rectangle(int x , int y)//parameterized constructor definition
 {
 length=x;
 width=y;
}
int rectArea()
{
 return (length * width);
}
}

class RectangleArea
{
 public static void main(String args[])
 {
 Rectangle r = new Rectangle();
Rectangle r1 = new Rectangle(15,20);//calling constructor
 int area = r1.rectArea();
 System.out.println("Area = " + area);
 area = r.rectArea();
 System.out.println("Area = " + ar ea);
}
}

Constructor overloading
A class can have multiple constructors. If more than one constructor is used in a class, it is known as constructor overloading. All the constructors have the same name as the corresponding class, and differ in terms of number of arguments, data types of argument or both.

WAP that demonstrate the concept of constructor overloading
class Account
{
  int accno;
 double balance;
 Account() //constructor1
 {
 accno=1024;
 balance=5000.55;
 }
 Account(int acc) //constructor2 with one argument
 {
 accno=acc;
 balance=0.0;
 }

 Account(int acc, double bal) //constructor3,with two
 //arguments
 {
 accno=acc;
 balance=bal;
 }

 void display()
 {
 System.out.println("Account no.=" +accno);
 System.out.println("Balance=" +balance);
 }
 } //end of class definition

class OverloadCons
{
 public static void main(String args[])
 {

 





 Account a1 = new Account();
 Account a2 = new Account(123);
 Account a3 = new Account(12,3456.50);
 a1.display();
 a2.display();
 a3.display();
}
}  

this keyword
The keyword this is useful when we need to refer to instance of the class from its method. The keyword helps us to avoid name conflicts. As we can see in some program we have declare the name of instance variable and local variables same. Now to avoid the confliction between them we use this keyword.

class Rectangle
{
 int length, breadth;
 void show(int length, int breadth)
{
 this.length = length;
 this.breadth = breadth;
 }
 int calculate()
{
 return(length * breadth);
 }
}

public class UseOfThisOperator
{
 public static void main(String[] args)
{
 Rectangle rectangle=new Rectangle();
 rectangle.show(5, 6);
 int area = rectangle.calculate();
 System.out.println("The area of a Rectangle is: " + area);
 }
}

Garbage Collection
The process of deallocation of memory that is reserved at runtime for an object is known as garbage collection. In Java memory space for an object is reserved when the object is created.

Such memory space later released for reallocation. In C++ such process done by using delete operator but in Java it is done automatically. The garbage collection works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.

Object as parameter
In java we can also pass object as function argument. The following example shows this technique:
class Test
{
 int a,b;
 Test(int i, int j)
{
 a=i;
 b=j;

}
boolean equals(Test t)
{
 if(t.a==a && t.b==b)
 {
 return true;
 }
 else
 return false;
 }
 }


class PassOb
{  
 public static void main(String args[])
 {
 Test t1 = new Test(11,22);
 Test t2 = new Test(11,22);
 Test t3 = new Test(1,1);
 System.out.println("t1 == t2 " + t1.equals(t2));
 System.out.println("t1==t3 " + t1.equals(t3));
 }
}

Returning object by a function
Like any normal instance variable, we can also return object form inside a function.
Program that demonstrate the concept of returning an object by a function:  
class Test
{
 int a;
Test (int i)
{
 a=i;
}

 Test incByTen()
{
 Test temp = new Test(a+10);
 return temp;
 }
 }

class RetOb
{
 public static void main(String args[])
 {
 Test ob1 = new Test(2);
 Test ob2;
 ob2 = ob1.incByTen();
 System.out.println("ob1.a: " +ob1.a);
 System.out.println("ob2.a: " + ob2.a);
 ob2 = ob2.incByTen();
 System.out.println("ob2.a after second increse : " +ob2.a);
 }
 }

Static members
The members that are declared static are called static members. There are two types of static members. They are static instance variable and static method. Static members are accessed before any objects of its class are created and without reference to any object.
Static variables declared as static are global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instance of the class shares the same static variable.

The most common example of a static member is main(). main() is declared as static because it must be called before any object exists.

Static method
Those methods that are declared as static are known as static methods. Static methods have several properties that are:
- They can only call other static methods
- They can only access static data.
- They cannot refer to this or super in any way.
- We can call static method from another class using classname.funtionname
Example:
class MathOperation
{
 static double mul(double x, double y)
 {
 return(x*y);
 }
 static double divide(double x, double y)
 {
 return(x/y);
 }

}

class MathApplication
{

 public static void main(String args[])
 {
 double a= MathOperation.mul(2.5,3.5);
 double b = MathOperation.divide(4.0,2.0);
 System.out.println("a= " +a);
 System.out.println("b= " +b);
 }

 } 

No comments:

Post a Comment

Contact Form

Name

Email *

Message *