Nested
class
A class
defined within another class is known as nested class. The scope of a nested class
is bounded by the scope of its enclosing class. Thus if class B is defined within
class A, then B is known to A, but not outside of A.
A nested
class (that is inner class) has access to the members, including private members
of the class in which it is nested. However, the enclosing class does not have access
to the members of the nested class.
WAP that
demonstrate the concept of an inner class
class
Outer
{
int outer_x=100;
void test()
{
Inner inn = new Inner();
inn.display();
}
class Inner// this is a inner class
{
void display()
{
System.out.println("Display:outer_x = "
+outer_x);
}
}
}
class
InnerClassDemo
{
public static void main(String args[])
{
Outer out = new Outer();
out.test();
}
}
Method
calling techniques
There
are two techniques that a computer language can call its subroutine.
1. Call-by-value
This method
copies the value of an argument into the formal parameter of the subroutine.
Therefore,
any changes made to the parameter of the subroutine have no effect on the argument.
class
Test
{
//simple types are pass by value
void calculate(int i , int j)
{
i = i*2;
j = j/2;
}
}
class
CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: "
+a + " " +b);
ob.calculate(a,b);
System.out.println("a and b after call: "
+a + " " +b);
//System.out.println("i and j after method
calculation: " +ob.i + " " +ob.j);
}
}
2. Call-by-reference
In this
method, a reference to an argument (not the value of the argument) is passed to
the parameter. Inside the subroutine, this reference is used to access the actual
argument specified in the call.
This means
that changes made to the parameter will affect the argument used to call the subroutine.
//objects
are passed by reference
class
Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
//simple types are pass by value
void calculate(Test ob)
{
ob.a = ob.a*2;
ob.b = ob.b/2;
}
}
class
CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15,20);
System.out.println("ob.a and ob.b before call:
" +ob.a + " " +ob.b);
ob.calculate(ob);
System.out.println("ob.a and ob.b after call:
" +ob.a + " " +ob.b);
//System.out.println("i and j after method
calculation: " +ob.i + " " +ob.j);
}
}
No comments:
Post a Comment