Showing posts with label Methods. Show all posts
Showing posts with label Methods. Show all posts

10.1Access Control

Friday, August 21, 2009 Posted by Sudarsan 0 comments
As you know, encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute access control.

Java’s access specifier are public, private and protected.Java also defines a default access level.protected applies only when inheritance is involved.

Let’s begin by defining public and private.When a member of a class is modified the public specifier, then that member can be accessed by any other code. When a member of class is specified as private, then that member can only be accessed by other members of its class.

So, we can understand that why main() has always been preceded by the public specifier.It is called by code that is outside the program-that is, by the Java run-time system.

When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.

To understand the effects of public and private access, have a look at the fallowing example


// Access.java demonstrates the difference between public and private
/**
*
* @author Sudarsan
*/
class Access {

// Defining three fields with different access levels

int x;
public int y;
private int z;

//To initilize field Z

void setZ(int a)
{
z=a;
}

//To get Z value

int getZ()
{
return z;
}

}



// Creating Access Object

/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Access ob=new Access();

ob.x=10;
ob.y=20;

//This will cause an error because z is private in Access
// ob.z=30;

ob.setZ(30); // To initialize z we need to use this method

System.out.println("The Values of X, Y and Z are :"+ob.x+" "+ob.y+" "+ob.getZ());
}

}


As you can see, inside the Access class, x uses default access, y is explicitly specified as public.Field z is given private access.

Inside the main class, z cannot be used directly. It must be accessed through its public methods :setZ() and getZ().

Static Fields and Methods

These are used to define class variables and methods that belong to a class and not to any particular instance of the class. static associates the data members with a class and not the objects of the class.
Whn a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.The most common example of astatic member is main().

main() is declared as static because it must be called before any object exists.

Fields declared as static are, essentially, global variables.When objects of its class are declared, no copy of static variable is made.

All instances of the class share the same static variable.

If we want to declare a method as static we need to fallow the several restrictions

1. static methods can only call other static methods.
2. They must only access static data.
3. We cannot refer to this or super in any way.

If we want to manipulate in order to initialize our static variables, we can declare a static block which gets executed exactly once, when the class is first loaded.

Have a look at the fallowing examples to know more about static


// Using static variables, methods and blocks
/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/

static int x=4;
static int y;

static void calc(int a)
{
System.out.println("Value of A : "+a);
System.out.println("Value of X : "+x);
System.out.println("Value of Y : "+y);
}

static
{
System.out.println("Static Block.......");

y=x*3;
}
public static void main(String[] args) {
// TODO code application logic here

calc(3);
}

}


From the above example we can observe, when the Main class is loaded, all of the static statements executed first. Initially x is set to 4, then the static block executed and finally y is initialized to 12.

Here is the output of the program

Static Block.......
Value of A : 3
Value of X : 4
Value of Y : 12

If you wish to call a static method from outside its class, you can do so using the fallowing general form.

classname.method()

Here is an example to demonstrate the above situation.


// Static.java

/**
*
* @author Sudarsan
*/
class Static {

static int i=10;
static int j=20;

static void calc()
{
System.out.println("Value of I : "+i);
}

}



// Main class is used to call static method

/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

Static.calc();

System.out.println("Value of J : "+Static.j);
}

}


Here you can see that inside main(), the static method calc() and the static variable j are accessed outside of their class.

Here is the output of the program

Value of I : 10
Value of J : 20

final Keyword

In Java a variable can be declared as final.By doing this we can prevent its contents from being modified. Which means that we must initialize final variable when it is declared.final is similar to const in C/C++/C#.

For example have look at the fallowing declarations

final int VAR1=1;
final int VAR2=10;
Labels:

10.Enhancing Methods of a Class

Thursday, August 20, 2009 Posted by Sudarsan 0 comments
The best way to develop and maintain a large program is to construct it from small, simple pieces, or modules. This technique is called divide and conquer.

There are three kinds of modules in Java, they are

1. Methods
2. Classes
3. Packages

Methods are declared within classes. Classes are typically grouped into packages so that they can be imported into programs and reused.

Methods allow the programmer to modularize a program by separating its tasks into self-contained units. The statements in a method are written only once and hidden from other methods.

Using existing methods as building blocks to create new programs is a form of software reusability that allows programmers to avoid repeating code within a program.

A method class specifies the name of the method to call and provides the arguments that the called method requires to perform its task. When the method call completes, the method returns either a result or simplify control to its caller.

Methods are used to access the variables that are defined in a class. A method is an interface to a class.
Parameterized methods need some extra information for its execution. The extra information is passed to the method by using arguments. Arguments are also known as parameters of the methods.

Defining Parameterized Methods:

Parameterized methods use parameters to process data and generate an output. The output of a parameterized method is not static and depends on the value of the parameters passed. Parameters in a parameterized method allow the method to be generalized.

Defining a Method with Parameters

The syntax of any method that have parameters:

void method_name(parameter_list)
{
statements;
}

In the preceding syntax, the return type specifies void.




Defining a Method that Returns a Value:

We can define a method that can return a value instead of just computing results and displaying them. The return type of a method is specified to the Java compiler in the method declaration statement.

The return type of a method can be of any primitive data type or abstract data type. The value is returned from a method using the return keyword followed by the value to be returned.

The methods that do not return any value have return type void.



Defining a Method that Returns a Value

The syntax of any method that returns a value is:

return_type method_name(parameter_list)
{
statements;
return value;
}

In the preceding syntax, the return type specifies the type of data returned by the method and the return statement specifies the value returned.

Passing Parameters to a Method

Arguments can be passed to a method using two ways:

Call-by-value: Copies the value of the actual parameters to the formal parameters. Therefore, the changes made to the formal parameters have no effect on the actual parameters.

Call-by-reference: Passes the reference and not the value of the actual parameters to the formal parameters in a method. Therefore, the changes made to the formal parameters affect the actual parameters.

We can also pass arguments to the main() method at the run-time of a program.

Passing Arguments by Value:

In Java, when arguments of primitive data type, such as int and float are passed to a method then they are passed by value.

When arguments are passed by value, a copy of the actual argument is passed to the formal arguments of the called method, which is maintained at a separate memory location. Therefore, when the called method changes the value of the argument, the change is not reflected in the actual argument.

Passing Arguments by Reference:

In this we can pass a reference to an argument to the parameter of a method. In Java, the objects of abstract data type are passed by reference.

When arguments are passed to the method by reference then any change made to the formal argument by the called method is also reflected in the actual argument.

The argument passed by reference to the formal parameter has the same memory location as that of the actual parameter.

Passing Arguments at the Command Line:

Command-line arguments are used to provide information that a program needs at startup.

The main() method in Java is the first method to be executed, therefore the command-line arguments are passed to the main() method.

The main() method stores the command-line arguments in the String array object.

In Java, the syntax for command-line argument is:

public static void main(String args[])
{ //statements
} //End of main() method


In the preceding syntax, each of the elements in the array named args[] is a reference to the command-line arguments each of which is a String object.

Have a look at the fallowing examples to know more about Call by Value and Call By Reference.

Call By Value Example

//Simple types are passed by value

/**
*
* @author Sudarsan
*/
class CallByValue {

void swap(int x,int y)
{
int temp=x;
x=y;
y=temp;
}
}



// Main class is used to construct the CallByValue Object
/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

CallByValue val=new CallByValue();

int a=10,b=20;

System.out.println("A and B Before Swap :"+a+" "+b);

val.swap(a, b);

System.out.println("A and B After Swap :"+a+" "+b);

}

}


After compiling this program we can see the output as given below

A and B Before Swap :10 20
A and B After Swap :10 20

Which means the operations that occur inside the swap() method have no effect on the values of a and b used in the call, their values here did not change to 20 and 10.

Call By Reference Example


// Class CallByRef.java

/**
*
* @author Sudarsan
*/
class CallByRef {

int a,b;

//Parameter Constructor for the Class

CallByRef(int x,int y)
{
a=x;
b=y;
}

//Passing object as parameter for the method swap
void swap(CallByRef ref)
{
int temp=ref.a;
ref.a=ref.b;
ref.b=temp;
}

}




// Main method is used to construct the CallByRef object
/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

CallByRef val=new CallByRef(10,20);

System.out.println("A and B Values Before Swap :"+val.a+" "+val.b);

//Passing object referance as a parameter to the method swap

val.swap(val);

System.out.println("A and B Values After Swap :"+val.a+" "+val.b);

}

}


If we compile this program we can see the fallowing output

A and B Values Before Swap :10 20
A and B Values After Swap :20 10

As we can see, in this case, the actions inside the swap() method have affected the object used as an argument. Command Line Arguments Example


// This program accepts the arguments from the command line
/**
*
* @author Sudarsan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here

for(int i=0;i<=args.length;i++)
{
System.out.println(args[i]);
}
}

}


Compile the code and execute it with the fallowing command:

Java Main Welcome To Java

The output will be as follows:
Welcome
To
Java
Labels: