5. ClassesAndObjects2
5. ClassesAndObjects2
Tutorial 4
class Factorial
{ int fact(int n)
{
int result;
if(n==1) return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
// Another example that uses recursion.
class RecTest
{ int values[];
RecTest(int i)
{ values = new int[i];
}
// display array -- recursively
void printArray(int i)
{
if(i==0) return;
else printArray(i-1);
System.out.println("[" + (i-1) + "] " + values[i-1]);
}
}
class Recursion2
{
public static void main(String args[])
{
RecTest ob = new RecTest(10);
int i;
for(i=0; i<10; i++)
ob.values[i] = i;
ob.printArray(10);
}
}
[0] 0
[1] 1
[2] 2
[3] 3
[4] 4
[5] 5
[6] 6
[7] 7
[8] 8
[9] 9
static
static member is defined for the class itself & exist independently of any
object of that class
To create such a member, precede its declaration with the keyword static.
clsName.varName;
clsName.methodName(args);
Static variable :
}
static method :
class OuterClass
{
...
class NestedClass
{
...
}
Nested class has access to the members, including the private members, of
the class in which it is nested.
Enclosing class does not have access to the members of the nested class .
Nested class types:
static : It must access the members of its enclosing class through an object. ie, it cannot
refer to members (non static) of its enclosing class directly. It can access static data
members of outer class including private.
class OuterClass
{
static class StaticNestedClass
{
...
}
class InnerClass
{
...
}
}
class Outer
{ int outer_x = 100;
void test()
{ Inner inner = new Inner();
inner.display();
}
class Inner
{ void display()
{ System.out.println(“display: outer_x = “ + outer_x); }
}
}
class InnerClassDemo
{ public static void main(String args[])
{ Outer outer = new Outer();
outer.test();
} }
class Outer
{ int outer_x = 100;
void test()
{ Inner inner = new Inner();
inner.display(); }
void showY()
{ System.out.println(y); // error, y not known here! }
class Inner
{ int y = 10; //y is local to Inner
void display()
{ System.out.println(“display: outer_x = “ + outer_x); }
}
}
class InnerClassDemo
{ public static void main(String args[])
{ Outer outer = new Outer();
outer.test();
} }
Command-Line Arguments
Passing information into a program during the execution is carried out by passing command line arguments to
main().
Command-line is the information that directly follows the program name on the command line when it is
executed.
They are stored as strings in a string array passed to the args parameter of main().