2.10
Static Members static int cal; static float min = 1; static void display(int x)
• • •
They can only call other static methods. They must only access static data. They cannot refer to this or super in any way. (The keyword super relates to inheritance and is described in the next topic).
//Demonstration of static members class MyWork { static int x = 10; static int count = 1; static void display() { System.out.println("Static has initialized..."); } static void increment() { System.out.println("Function call : "+count); count++; } } class StaticMember { public static void main(String args[]) { MyWork.display(); //statement1 System.out.print("Value of x: "); System.out.println(MyWork.x); //statement2 MyWork.increment(); //statement3 MyWork.increment(); //statement4 MyWork.increment(); //statement5 } } Program 2.9 Program using static variables and methods
// Call by value. class Test { void meth(int i, int j) { i++; j++; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 22, b = 93;
System.out.print("a and b before call: "); System.out.println(a + " " + b); ob.meth(a, b); System.out.print("a and b after call: "); System.out.println(a + " " + b); } } Program 2.10 Example of Call by Value
// Objects are passed by reference. class Test { int a, b; void meth(Test o) { o.a++; o.b++; } } class CallByRef { public static void main(String args[]) { Test ob = new Test(); ob.a = 22; ob.b = 93; System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } } Program 2.11 Example of Call by Reference
//A method returning object class Square { int n; Square(int x) { n = x; } Square change() { Square temp = new Square(n); temp.n = temp.n * temp.n; return(temp); } }
class ReturnObject { public static void main(String args[]) { Square s = new Square(8); Square t; t = s.change(); System.out.println("Square of 8 is: "+t.n); } } Program 2.12 Method which returns object
//Finding factorial using recursion class Factorial { int fact(int n) { if(n==1) return 1; //statement1 else return(n*fact(n-1)); } public static void main(String args[]) { Factorial f = new Factorial(); System.out.print("Factorial of 4:"); System.out.println(f.fact(4)); System.out.print("Factorial of 5:"); System.out.println(f.fact(5)); System.out.print("Factorial of 6:"); System.out.println(f.fact(6)); } } Program 2.13 Calculating factorial using recursion
Nested and inner classes
// Demonstration of an inner class. class Outer //Outer class { int out_x; Outer(int x) { out_x = x; } void test() { Inner inner = new Inner(); inner.display(); } class Inner //Inner class { void display() {
System.out.print("Value: out_x ="); System.out.println(out_x); } } } class InnerClass { public static void main(String args[]) { Outer outer = new Outer(15); outer.test(); } } Program 2.15 Inner and Outer class demo