Upload
dhanraj-kannan
View
8
Download
0
Embed Size (px)
DESCRIPTION
Methods
Citation preview
A Closer look at Methods and Classes(Chapter 7)
Overloading
Polymorphism
• Compile Time or Static Polymorphism– Overloading
• RunTime or Dynamic Polymorphism– Overriding super class methods– Implementing interfaces to classes
Overloading Methodsclass Calculator {
public static int add(int a, int b) {
return a + b;
}
public static int add(int a, int b, int c) {
return a + b;
}
public static double add(double a, double b) {
return a + b;
}
Overloading public static double add(int a, double b) {
return a + b;
}
public static double add(double a, int b) {
return a + b;
}
}
Overloadingclass UseCalculator {
public static void main(String[] args) {
System.out.println(add(2, 3));
System.out.println(add(1, 2, 3));
System.out.println(add(34.5, 24.6));
System.out.println(add(5, 38.8));
System.out.println(add(56.4, 25));
}
}
//Demonstrate method overloading.class Overload {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 parameterdouble test(double a) {System.out.println("double a: " + a);return a*a; } }class OverloadDemo {public static void main(String args[]) {Overload ob = new Overload();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);}}
//Automatic type conversions apply to overloading.class OverloadDemo1 {void test() {System.out.println("No parameters");} //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 parametervoid test(double a) {System.out.println("Inside test(double) a: " + a); } }class OverLoading {public static void main(String args[]) {OverloadDemo1 ob = new OverloadDemo1();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)}}
• Overloading Constructors• class Box {double width;double height;double depth; //constructor used when all dimensions specifiedBox(double w, double h, double d) {width = w; height = h; depth = d;} //constructor used when no dimensions specifiedBox() {width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } //constructor used when cube is createdBox(double len) {width = height = depth = len;} //compute and return volumedouble volume() {return width * height * depth; } }class OverloadCons {public static void main(String args[]) { //create boxes using the various constructorsBox mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7);double vol; //get volume of first boxvol = mybox1.volume();System.out.println("Volume of mybox1 is " + vol); //get volume of second boxvol = mybox2.volume();System.out.println("Volume of mybox2 is " + vol); //get volume of cubevol = mycube.volume();System.out.println("Volume of mycube is " + vol);}}
• Using Objects as Parameters
// Objects may be passed to methods.class Test {int a, b;Test(int i, int j) {a = i;b = j;}// return true if o is equal to the invoking objectboolean equals(Test o) {if(o.a == a && o.b == b) return true;else return false;}}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.equals(ob2));System.out.println("ob1 == ob3: " + ob1.equals(ob3));}}
// Here, Box allows one object to initialize another.class Box {double width; double height; double depth; //construct clone of an objectBox(Box ob) { // pass object to constructorwidth = ob.width; height = ob.height; depth = ob.depth;}// constructor used when all dimensions specifiedBox(double w, double h, double d) {width = w; height = h; depth = d;} //constructor used when no dimensions specifiedBox() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box} //constructor used when cube is createdBox(double len) {width = height = depth = len;}//compute and return volumedouble volume() {return width * height * depth;}}class OverloadCons2 {public static void main(String args[]) { //create boxes using the various constructorsBox mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); Box
myclone = new Box(mybox1);double vol;//get volume of first boxvol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol);// get volume of second boxvol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol);//get volume of cubevol = mycube.volume(); System.out.println("Volume of cube is " + vol);//get volume of clonevol = myclone.volume(); System.out.println("Volume of clone is " + vol);}}
Argument Passing
• call-by-value• Method copies the value of an argument into the formal parameter of the
subroutine.
• Therefore, changes made to the parameter of the subroutine have no effect on the argument
• 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.
• ---------------------------------------------------------------------------------------------
• In Java, when you pass a simple type to a method, it is passed by value.
• Thus, what occurs to the parameter that receives the argument has no effect outside the method.
// call by value
class ValueTest {public static void main (String [] args) {int a = 1;ValueTest vt = new ValueTest();System.out.println("Before modify() a = " + a);vt.modify(a);System.out.println("After modify() a = " + a);}void modify(int number) {number = number + 1;System.out.println("number = " + number);}
}
//Simple types are 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);}}
import java.awt.Dimension;class ReferenceTest {public static void main (String [] args) {Dimension d = new Dimension(5,10);ReferenceTest rt = new ReferenceTest();System.out.println("Before modify() d.height = " + d.height);rt.modify(d);System.out.println("After modify() d.height = "+ d.height);}void modify(Dimension dim) {dim.height = dim.height + 1;System.out.println("dim = " + dim.height);}}
//Objects are passed by reference.class Test1 {int a, b;Test1(int i, int j) {a = i;b = j;}//pass an objectvoid meth(Test1 o) {o.a *= 2;o.b /= 2;}}class CallByRef {public static void main(String args[]) {Test1 ob = new Test1(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);}}
Function Returning Objects//Returning an object.class Test3 {int a;Test3(int i) {a = i;}Test3 incrByTen() {Test3 temp = new Test3(a+10);return temp;}}class RetOb {public static void main(String args[]) {Test3 ob1 = new Test3(2);System.out.println("ob1.a: " + ob1.a);Test3 ob2;ob2 = ob1.incrByTen();System.out.println("ob2.a: " + ob2.a);//ob2 = ob2.incrByTen();//System.out.println("ob2.a after second increase: "+ ob2.a);}}
// Will discuss one example after Inheritance
• 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.• Instance variables declared 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.• illegal to refer to any instance variables inside of a static method.
• public class StaticDemo {• //instance variable is automatically initialized to its default value.• int x;• //class variable is also initialized to its default value.• static int y;• void x(){• }• static void y(){• }• static{• System.out.println("Static code block initialized");• y =20;• }• static void add(int i,int j){System.out.println(i+j);• }• static void anotherStaticMethod(){• System.out.println(y);• y();• }• public static void main(String args[]){• //local variables should be always initialized.• int k=0;• System.out.println("Main method entered");• System.out.println("Value of y"+y);• System.out.println("Value of k"+k);• y();• StaticDemo sd = new StaticDemo();• sd.x();• sd.x =10;• add(10,20); } }
// Defines one value for the whole class
class staticBox {static int width ;static int depth ;static int height;}public class StaticBoxDemo {public static void main (String args[]){staticBox sb1 = new staticBox();sb1.width =10;sb1.depth = 10;sb1.height=10;System.out.println("box 1 "+sb1.width);System.out.println("box 1 "+sb1.depth);System.out.println("box 1 "+sb1.height);System.out.println();staticBox sb2 = new staticBox();sb2.width =20;System.out.println("box 2 "+sb2.width);System.out.println("box 2 "+sb2.depth);System.out.println("box 2 "+sb2.height);System.out.println();staticBox sb3 = new staticBox();System.out.println("box 3 "+sb3.width);System.out.println("box 3 "+sb3.depth);System.out.println("box 3 "+sb3.height);}}
//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);}}
• To call a static method from outside its classclassname.method( )
Ex: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);}}
• Final
• final int FILE_NEW = 1;
• final int FILE_OPEN = 2;
• final int FILE_SAVE = 3;
• final int FILE_SAVEAS = 4;
• final int FILE_QUIT = 5;
• uppercase identifiers for final variables• final variable is essentially a constant.
• Public static final double PI = 3.14;
Types of Variables
• Instance variables, Local variables, final variables, static variables.
• IV:– Variable declared inside class.
– Memory will be allocated when object is created.
– JVM initializes the variable with default values.
– Scope is within the class.
• LV: – Variable declared inside method
– Memory will be allocated when you call the method.
– Initialize LV before using, else errors.
– Scope is within the method.
• FV:– Variable which are declared with final keyword.
– Assign the values when you declare.
– Once assigned, value is fixed and cannot be changed.
– IV, LV can be final variables.
• SV:– Variable declared inside class with static keyword.
– Memory will be allocated when class is loaded into the memory.
– JVM initializes the static variable with default values.
– Scope is within the class
– Static keyword is not allowed for LV.
Primitive variables Reference variables (Object)
Variables declared with any of the primitive data types
Variables declared with any of the class types
Memory allocation will be done for the primitive variables based on the primitive data type used.
8 byte of memory will be allocated for reference variables.
Initial values depend on the data type used.
Null is the default value.
• IV are not allowed inside the static block and static method directly (Can declare, but could not access).
• Instance method calling is not allowed inside static block and static method directly.
• IV, SV, Instance methods and static methods are allowed inside the instance method directly.
• We can call the instance variables and instance method with object because instance method belongs to object.
• Static variables and static methods can be called with class name because static members belongs to class.
• Static members can also be referred with object.
Inner Classes
• Access to all of the variables and methods of its outer class
//Demonstrate an inner class.• class Outer {• int outer_x = 100;• void test() {• Inner inner = new Inner();• inner.display();• // System.out.println(a);• }• //this is an inner class• class Inner {• int a = 2;• void display() {• System.out.println("display: outer_x = " + outer_x);• }}• // System.out.println(a);• }• class InnerClassDemo {• public static void main(String args[]) {• Outer outer = new Outer();• outer.test();• }• }
• class Inner is known only within the scope of class Outer. • Members of the inner class are known only within the scope of the inner class and may not be used by the outer
class.
Command-Line Arguments
• A command-line argument is the information that directly follows the program’s name on the command line when it is executed.
• class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}} String[] args1={"aaa","bbb","ccc"};• int d = args1.length; //3• System.out.println(d);
Simple String ---String[] arg={"aaa","bbb","ccc"}; arg.length();//3
Array of String--- String[] arg={"aaa","bbb","ccc"}; arg.length;//3
• A public instance variable length is associated with each array that has been instantiated.
• The variable length contains the size of the array. • The variable length can be directly accessed in a
program using the array name and the dot operator.• This statement creates the array list of six components
and initializes the components using the values given. int[] list = {10, 20, 30, 40, 50, 60};
Here, list.length is 6.
Arrays and the Instance Variable length
• This statement creates the array numList of 10 components and initializes each component to 0.
int[] numList = new int[10]; The value of numList.length is 10. • These statements store 5, 10, 15, and 20, respectively, in the first
four components of numList.numList[0] = 5;numList[1] = 10;numList[2] = 15;numList[3] = 20;
• The value of numList.length is still 10.
• You can store the number of filled elements, that is, the actual number of elements, in the array in a variable, SAYnoOfElement. It is a common practice for a program to keep track of the number of filled elements in an array.
Arrays and the Instance Variable length
• Loops used to step through elements in array and perform operations.
• int[] list = new int[100];int i;
//process list[i], the (i + 1)th element of listfor (i = 0; i < list.length; i++)
//inputting data to listfor (i = 0; i < list.length; i++) list[i] = console.nextInt();
//outputting data from listfor (i = 0; i < list.length; i++) System.out.print(list[i] + " ");
– Remember to start loop counter from 0 because Array index starts from 0.
Processing One-Dimensional Arrays
Arrays • Some operations on arrays:
– Initialize– Input data– Output stored data– Find largest/smallest/sum/average of
elements
Example 9_3
double[] sales = new double[10];int index;double largestSale, sum, average;
Code to Initialize Array to Specific Value (10.00)
for (index = 0; index < sales.length; index++) sales[index] = 10.00;
Note: .length NOT .length()It is a variable not a method.
Code to Read Data into Array
for (index = 0; index < sales.length; index++) sales[index] = console.nextDouble();
Integer.parseInt()
• Tedious job to enter the values each time before the compilation in the method itself. Now if we want to enter an integer value after the compilation of a program and force the JVM to ask for an input, then we should use Integer.parseInt(string str).
• Integer is a name of a class in java.lang package and parseInt() is a method of Integer class which converts String to integer
public class SimpleParseInt {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
if (a % 2 == 0 )
System.out.println("The number is even");
else
System.out.println("The number is odd");
if (a > 0)
System.out.println("The number is positive");
else System.out.println("The number is negative");
}
}
class He{int l,w;
void show(int b,int a){l=b; w=a;}int cal(){return l*w;}}class ParseInt{
public static void main(String arg[]){He h=new He();int d = Integer.parseInt(arg[0]); int e = Integer.parseInt(arg[1]); h.show(d,e); System.out.println(" you have entered these values : " + d + " and " + e); int area = h.cal(); System.out.println(" area of a rectange is : " + area);
}}