Tuesday, December 18, 2007

JAVA 2.0 NOTES



JAVA 2.0 NOTES

Garbage collection

When no reference to object exits, the object no longer needed, the memory occupied by the object is reclaimed. This is called garbage collection. Java periodically does garbage collection.

Finalizer :

Finalizer method is the exact opposite of constructor method. They are called just before the object is garbage collected and its memory is reclaimed. All cleanup operations are performed in this method.
protected void finalize( )
{ }

Methods overloading

Methods overloading is creating different methods with same name but with different parameters. This is the one type of creating polymorphism in Java
Example for method overloading and constructor overloading

Example 9:

Box( )

{

int depth;

int width;

int height;

Box(int w, int d, int h)

{witdth = w; height = h; depth = d;

}

Box(int a)

{

witdth = a; height = a; depth = a;

}

Box( )

{

witdth = 1; height = 1; depth = 1;

}
void show( )

{

System.out.println(width * height * depth);

}

void show(int a)

{System.out.println("Width = " + w);

System.out.println("Depth = " + d);

System.out.println("Height = " + h);

System.out.println("Cube is " + (width * height * depth )) ;}}



class boxdemo

{

public static void main(String args[ ])

{
Box b1 = new Box(3,4,5);

Box b2 = new Box(5);

Box b3 = new Box( );b1.show(1);

b2.show( );b3.show( );

}



}





Method Overriding

Method overriding is creating a method in the derived class that has the same name arguments
as in the superclass. This new method hides the superclass method.

Recursion

Recursion is the process of defining something in terms of itself. A method that calls itself is said to be recursive.

Example 10:

class factorial

{

int fact(int n)

{

int result;if(n==1) return 1;

result = fact(n----1) * n;

return result;}

}

class recurse

{
public static void main(String a[ ])

{factorial f = new factorial( );

System.out.println("Fact of 3 is "+f.fact(3));

}

}

Nested Class

It is possible to nest a class definition within another and treat the nested class like any other
method of that class. An inner class is a nested class whose instance exists within an instance of
its enclosing class and has direct access to the instance members of its enclosing instance.


class enclosingClass

{

class innserClass

{}

}

Example :

class outclass

{

int a =10;

public void m1( )

{

System.out.println("This is inner class method");

inclass in = new inclass( );

in.m2( );

}

class inclass

{

public void m2( )
{

System.out.println("This is inner class method");

System.out.println("a = "+ a);

}

}

public static void main(String arg[ ])

{

outclass out = new outclass( );

out.m1( );

}

}




No comments: