Methods and Classes

Methods and classes:

  • Two or more methods are said to be in same class that share the same name as long as their parameter declaration are different.

  • And these case method said to be overloaded is called method overloading.It support polymorphism.

  • Overloaded method is invoked uses the type and number of arguements as its guide to detremine which version of the overloaded method to call.

Example:

class overloaddemo{
void test(){
System.out.println("no parameters");
}
void test(int a){
System.out.println("a:" + a);
}
void test(int a,int b){
System.out.println("a and b" + a +" "+ b);
}
double test(double a){
System.out.println("double a" + a);
return a*a;
}
}
public class overload{
public static void main(String args[]){
overloaddemo ob = new overloaddemo();
double result;
ob.test();
ob.test(10);
ob.test(10,20);
result = ob.test(123.5);
System.out.println("Result of obtest(123.5)"  + result);
}
}

Result: no parameters

a:10

a and b10 20

double a123.5

Result of obtest(123.5)15252.25

  • Java standards class library includes absolute value method called abs()
  • the compiler to choose the right specific version of the particular circumstances.

Examples:

class box{
double width;
double height;
double depth;
box(double w,double h,double d){
width = w;
height = h;
depth = d;
}
box(){
width = 1;                                       (-1 is used to indicate uninitialized the box)
height = -1;
depth = -1;
}
box(double len){
width = depth = height = len;
}
double volume(){
return depth * height * width;
}
}
public class overloads{
public static void main (String args[]){
box mybox = new box(10,20,15);
box mybox1 = new box();
box mycube = new box(7);
double vol;
vol = mybox.volume();
System.out.println("Volume is " + vol);
vol = mybox1.volume();
System.out.println("volume is " + vol);
vol = mycube.volume();
System.out.println("volume is " + vol);
}
}

A closer look at argument passing:

  • Argument passes the two types, as primitive as call by value and reference as call by reference.
  • value (int i, int j) reference (int o)
  • Example:
class test{
void meth(int i, int j){
i *= 2;
j /= 2;
}
}
public 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);
}
}
  • When you pass an object to a method, the situation changes dramatically, because objects are passed by what is effectively call-by-reference.
  • when you pass this reference to a method, the parameter that receives it will refer to the same object as that referred to by the argument.
  • This effectively means that objects act as if they are passed to methods by use of call-by-reference.
  • Example:
class test{
int a,b;
test(int i,int j){
a = i;
b = j;
void meth(test o){
o.a *= 2;
o.b/ = 2;
}
}
public class callbyobj{
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);
}
}

Recursion:

  • A method that call itself is called recursive.Recursion:

  • It is the attribute that allows the method to call by itself.

  • fact is called (with n-1)

  • The fact is called with an argument of 1.

  • When a method calls the new local variable and parameter are allocated storage on the stack and the method code is executed from the start.

  • As each recursive call return, the old local variable and parameter are removed from the stack.

    While writing recursive methods the IF statement is used the call the statement.In these it return the statement.

Example:

class rectest{
int values[];
rectest (int i){
values = new int[i];
}
void printarray(int i){
if(i==0)return ;
else printarray(i-1);
System.out.println("["+(i-1)+"]"  + values [i-1]);
}
}
public class recursions2 {
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);
}
}
  • The recursive method println() statements helps to see the what is going on or abort the execution.( to see mistakes)

  • The printArray() prints the first i in the list elements in the array values.

In these case the fact is used to return the factorial number.

Example:

class factorial{
int fact(int n){
int result;
if(n==1)return 1;
result = fact( n-1) *n;
return result;
}
}
public 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));
}
}

Introduction to access controls:

  • Encapsulation links the data with code that manipulates it.Through the encapsulation what part of program can control the member of the class and prevent misuse.
  • Java access modifiers are public,private,protected.It also has default modifiers.
  • The member of the class is specified by the private then that member can only be accessed by other member of its class.
  • When a member of class is modified by public then that member can be accessed by any other code.
  • It is also called by code that outside the program.

Understanding Logic:

  • when member is declared as static it can accessed before any objects of its class declared.

  • The examples of static are main().

static restrictions:

  • they can only directly call other static methods.
  • they can only access static data.
  • they cannot relate to THIS and SUPER in any way.

Examples:

  • static intilization blocks, static methods,static variables.
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);
}
}
  • The three println() statements refer to the two static variables a and b, as well as to the local variable x.

Introducing Final:

  • A field can be declared as model.

  • you can give it in a value when its declared.

  • you can assign a value within a constructor.

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;

  • These are the subsequent parts of the program to coding convention to choose all uppercase identifiers for FINAL fields.
  • The parameter FINAL prevents it from being changed within method.
  • The local variable FINAL prevents it from assigned value more than one.

Arrays Revisited:

  • All array has the variable that will always hold the size of the array.
  • The size of the array means the number of the elements that array can hold.It is found in the length instance variable.

Example:

class length{
public static void main(String args[]) {
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};
int a3[] = {4, 3, 2, 1};
System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}

Introducing nested and inner classes:

  • It is possible to define the class within another class such as nested class.

  • It is of two types:

    static nested class

unstatic nested class.

  • Most important class is inner class.An inner class is an nonstatic nested class.

Examples:

  class Outer {
  int outer_x = 100;
void test() {
for(int i=0; i<10; i++) {
class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
inner.display();
}
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}

Exploring the String class:

  • The first thing to understand about strings is that every string you create is actually an object of type String.

  • System.out.println("This is a String, too");

  • The string "This is a String, too" is a String object.

  • Java defines peer classes of String, called StringBuffer and StringBuilder

Example:

class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " + strOb1.length());
System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}
  • These are 3 methods,
  • boolean equals(secondStr)
  • int length( )
  • char charAt(index)

Commandline Arguements:

  • A command-line argument is the information that directly follows the program’s name on the command line when it is executed.
  • String array stored in the args parameter of main()
  • Example:
public class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}

Varags:

variable length argument:(1st condition)

  • A method that takes a variable number of arguments is a varargs method.
  • Example:
class PassArray {
static void vaTest(int v[]) {
System.out.print("Number of args: " + v.length + " Contents: ");
for(int x : v) System.out.print(x + " ");
System.out.println();
}
public static void main(String args[]) { // Notice how an array must be created to // hold the arguments.
int n1[] = { 10 };
int n2[] = { 1, 2, 3 };
int n3[] = { };
vaTest(n1); // 1 arg
vaTest(n2); // 3 args
vaTest(n3); // no args
}
}
  • v is an array.
  • It can be handled by 2 ways:
  • The maximum number of arguments was small and you create the overloaded versions of the method.

Varargs:(2nd condition)

  • It uses varag.
  • The first three arguments used in a call to doIt( ) are matched to the first three parameters.
  • Examples:
public class VarArgs {
static void vaTest(int ... v) {
System.out.print("Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
public static void main(String args[])
{
vaTest(10);
vaTest(1, 2, 3);
vaTest();
}
}
  • Here is a reworked version of the vaTest( ) method that takes a regular argument and a variable-length argument:

  • 3rd condition:

  • static void vaTest(String msg, int ... v)

  • msg is a normal parameter and v is a varag parameter.There is no two varag arguements are used continously.

  • After varag element no more varag arguements are used.

Examples:

       int doIt(int a, int b, double c, int ... vals, boolean stopFlag) { // Error!

       int doIt(int a, int b, double c, int ... vals, double ... morevals) { // Error!

Ambiguity:

  • This program will contain error and will not compile.
  • Example:

    class VarArgs4 {
    static void vaTest(int ... v) {
    System.out.print("vaTest(int ...): " + "Number of args: " + v.length + " Contents: ");
    for(int x : v)
    System.out.print(x + " ");
    System.out.println();
    }
    static void vaTest(boolean ... v) {
    System.out.print("vaTest(boolean ...) " + "Number of args: " + v.length + " Contents: ");
    for(boolean x : v) System.out.print(x + " ");
    System.out.println();
    }
    public static void main(String args[]) {
    vaTest(1, 2, 3); // OK
    vaTest(true, false, false); // OK
    vaTest(); // Error: Ambiguous!
    }
    }
    

results matching ""

    No results matching ""