Overloading Methods • InJava it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. • When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. • Method overloading is one of the ways that Java implements polymorphism.
3.
• When anoverloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of the overloaded method to actually call. • Thus, overloaded methods must differ in the type and/or number of their parameters. • While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method.
4.
// Demonstrate methodoverloading. class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } • output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625
5.
• In overloading,return types do not play a role. • When an overloaded method is called, Java looks for a match between the arguments used to call the method and the method’s parameters. • However, this match need not always be exact.
6.
• In somecases Java’s automatic type conversions can play a role in overload resolution. • Method overloading supports polymorphism because it is one way that Java implements the “one interface, multiple methods” paradigm. class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(); ob.test(10, 20); ob.test(i); // this will invoke test(double) ob.test(123.2); // this will invoke test(double) } }
7.
Overloading Constructors class Box{ double width,height,depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width = -1; height = -1; depth = -1; Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; } } class OverloadCons { public static void main(String[] args) { Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } }
8.
Using Objects asParameters class PassOb { public static void main(String[] args) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equalTo(ob2)); System.out.println("ob1 == ob3: " + ob1.equalTo(ob3)); } } // Objects may be passed to methods. class Test { int a, b; Test(int i, int j) { a = i; b = j; } boolean equals(Test o) { if(o.a == a && o.b == b) return true; else return false; } }
9.
A Closer Lookat Argument Passing • In general, there are two ways that a computer language can pass an argument to a subroutine. • The first way is call-by-value. This method copies the value of an argument into the formal parameter of the subroutine. • The second way an argument can be passed is call- by-reference. In this method, a reference to an argument (not the value of the argument) is passed to the parameter. • When a simple type is passed to a method, it is done by use of call-by-value. Objects are passed by use of call-by-reference.
10.
// Simple typesare passed by value. class Test { void meth(int i, int j) { i *= 2; 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.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } } The output from this program is shown here: a and b before call: 15 20 a and b after call: 15 20
11.
Objects are passedby reference. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // pass an object void meth(Test o) { o.a *= 2; o.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.meth(ob); System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b); } } This program generates the following output: ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10
12.
Returning Objects • Amethod can return any type of data, including class types that you create. • Since all objects are dynamically allocated using new, don’t worry about an object going out-of- scope because the method in which it was created terminates. • The object will continue to exist as long as there is a reference to it somewhere in your program. • When there are no references to it, the object will be reclaimed the next time garbage collection takes place.
13.
• // Returningan object. class Test { int a; Test(int i) { a = i; } Test incrByTen() { 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.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: “ + ob2.a); } } • The output generated by this program is shown here: ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22
14.
Recursion • Java supportsrecursion. Recursion is the process of defining something in terms of itself. • As it relates to Java programming, recursion is the attribute that allows a method to call itself. • A method that calls itself is said to be recursive.
15.
• class Factorial{ • // this is a recursive method • 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)); • } • }
16.
Understanding static • Therewill be times when you will want to define a class member that will be used independently of any object of that class. • Normally a class member must be accessed only in conjunction with an object of its class. • However, it is possible to create a member that can be used by itself, without reference to a specific instance. • To create such a member, precede its declaration with the keyword static. • When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ).
17.
• Instance variablesdeclared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. • Methods declared as static have several restrictions: ■ They can only call other static methods. ■ They must only access static data. ■ They cannot refer to this or super in any way.
18.
• If youneed to do computation in order to initialize your static variables, you can declare a static block which gets executed exactly once, when the class is first loaded. • // Demonstrate static variables, methods, and blocks. class UseStatic { static int a = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } } • Here is the output of the program: Static block initialized. x = 42 a = 3 b = 12
19.
• Outside ofthe class in which static methods and variables are defined, can be used independently of any object. • To do so, you need only specify the name of their class followed by the dot operator. • For example, if you wish to call a static method from outside its class, you can do so using the following general form: • classname.method( ) class StaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); } } • Here is the output of this program: a = 42 b = 99
20.
Introducing final • Avariable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. • (In this usage, final is similar to const in C/C++/C#.) • For example: final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; • It is a common coding convention to choose all uppercase identifiers for final variables. Variables declared as final do not occupy memory on a per-instance basis. Thus, a final variable is essentially a constant. • The keyword final can also be applied to methods, but its meaning is substantially different than when it is applied to variables.
21.
Introducing Nested andInner Classes • It is possible to define a class within another class; such classes are known as nested classes. • The scope of a nested class is bounded by the scope of its enclosing class. • A nested 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.
22.
• There aretwo types of nested classes: static and non-static. • A static nested class is one which has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. • The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class.
23.
• // Demonstratean inner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class 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(); } } • Output from this application is shown here: display: outer_x = 100
24.
• // Thisprogram will not compile. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class class Inner { int y = 10; // y is local to Inner void display() { System.out.println("display: outer_x = " + outer_x); } } void showy() { System.out.println(y); // error, y not known here! } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } }