Uploaded by Sukanta Majumder

java ppt on methods

advertisement
METHODS
A Quick Overview of Methods
• At the most basic level, a method is a sequence of statements that has been collected together and
given a name. The name makes it possible to execute the statements much more easily; instead of
copying out the entire list of statements, you can just provide the method name.
• The following terms are useful when learning about methods:
 Invoking a method using its name is known as calling that method.
 The caller can pass information to a method by using arguments.
 When a method completes its operation, it returns to its caller.
 A method can pass information to the caller by returning a result.
Methods and Information Hiding
• One of the most important advantages of methods is that they make it possible for callers to ignore
the inner workings of complex operations.
• When you use a method, it is more important to know what the method does than to understand
exactly how it works. The underlying details are of interest only to the programmer who
implements a method. Programmers who use a method as a tool can usually ignore the
implementation altogether.
• The idea that callers should be insulated from the details of method operation is the principle of
information hiding, which is one of the cornerstones of software engineering.
Methods as Tools for Programmers
• Particularly when you are first learning about programming, it is important to keep in mind that
methods are not the same as application programs, even though both provide a service that hides
the underlying complexity involved in computation.
• The key difference is that an application program provides a service to a user, who is typically not
a programmer but rather someone who happens to be sitting in front of the computer. By contrast,
a method provides a service to a programmer, who is typically creating some kind of application.
• This distinction is particularly important when you are trying to understand how the applicationslevel concepts of input and output differ from the programmer-level concepts of arguments and
results. Methods like readInt and println are used to communicate with the user and play no role in
communicating information from one part of a program to another.
Method Calls as Expressions
• Syntactically, method calls in Java are part of the expression framework. Methods that return a
value can be used as terms in an expression just like variables and constants.
• The Math class in the java.lang package defines several methods that are useful in writing
mathematical expressions. Suppose, for example, that you need to compute the distance from the
origin to the point (x, y), which is given by
x2 + y2
• You can apply the square root function by calling the sqrt method in the Math class like this:
double distance = Math.sqrt(x * x + y * y);
• Note that you need to include the name of the class along with the method name. Methods like
Math.sqrt that belong to a class are called static methods.
The return Statement
• The return type of a method indicates the type of value that the method sends back to the calling location
• A method that does not return a value has a void return type.
• The return statement specifies the value that will be returned.
Its expression must conform to the return type.
• A return statement is required for a nonvoid method. The following method is logically correct, but it has a
compilation error, WHY ?
public static int xMethod(int n)
{
if (n > 0) return 1;
else if (n == 0) return 0;
else if (n < 0) return –1;
}
public static int xMethod(int n)
{
if (n > 0) return 1;
else if (n == 0) return 0;
else if (n < 0) return –1;
else return -2;
}
public static int xMethod(int n)
{
if (n > 0) return 1;
else if (n == 0) return 0;
else if (n < 0) return –1;
return -2;
}
Overloading
• Overloading allows different methods to have same name, but different signatures where signature can differ by
number of input parameters or type of input parameters or both. Overloading is related to compile time (or static)
polymorphism.
public class Method {
public static int method(int a) { return 10; }
public static char method(int a, int b) { return 'c'; }
public static void main(String args[])
{
System.out.println(method(1));
System.out.println(method(1, 2));
}
}
 We can have two ore more static methods with same
name, but differences in input parameters.
 We cannot overload two methods in Java if they
differ only by static keyword (number of parameters
and types of parameters is same).
 Unlike C++, Java doesn’t allow user defined
overloaded operators. Internally Java overloads
operators, for example + is overloaded for
concatenation.
 when method signature is same and the return type
is different the compiler will give error as the return
value alone is not sufficient for the compiler to
figure out which function it has to call.
Can we overload main() in Java?
public class OverloadMain {
// Normal main()
public static void main(String[] args) {
System.out.println(" Hi!! I am from normal main");
OverloadMain.main("Hello!! i am from Overloaded main ");
}
// Overloaded main methods
public static void main(String arg1) {
System.out.println("Hi, " + arg1);
OverloadMain.main("again!!! ", "i am a testtube main :)");
}
public static void main(String arg1, String arg2) {
System.out.println("Hi, " + arg1 + ", " + arg2);
}
}
Different ways of method overloading
Java can distinguish the methods with different method signatures. i.e. the methods can have same name but with
different parameters list (i.e. number of the parameters, order of the parameters, and data types of the parameters)
within the same class.
 Overloaded methods are differentiated based on the number and type of the parameters passed as an arguments
to the methods.
 We can not define more than one method with the same name, Order and the type of the arguments. It would be
compiler error.
 The compiler does not consider the return type while differentiating the overloaded method. But you cannot
declare two methods with the same signature and different return type. It will throw a compile time error.
If both methods have same parameter types, but different return type, then it is not possible.
Method overloading can be done by changing:
 The number of parameters in two methods.
 The data types of the parameters of methods.
 The Order of the parameters of methods.
public class Test
{
// Overloaded methods
public void fun(Integer i) {
System.out.println("fun(Integer ) "); }
public void fun(String name) {
System.out.println("fun(String ) "); }
public static void main(String [] args) {
Test ts= new Test();
ts.fun(null);
}
}
here the method arguments Integer and
String both are not primitive data types in
Java. That means they accept null values.
When we pass a null value to the
method1 the compiler gets confused
which method it has to select, as both are
accepting the null.
public class Test
{
// Overloaded methods
public void fun(Integer i) {
System.out.println("fun(Integer ) "); }
public void fun(String name) {
System.out.println("fun(String ) "); }
public static void main(String [] args) {
Test ts= new Test();
Integer arg = null;
ts.fun(arg);
}
}
here if the “arg” value is null due to the
result of the expression, then the null
value is passed to method1. Here we
wouldn’t get compile time error
because we are specifying that the
argument is of type Integer, hence the
compiler selects the method1(Integer i)
and will execute the code inside that.
Ambiguous Invocation
public class AmbiguousOverloading {
public static void main(String[] args) {
double x= max(1,2);
System.out.println(x);
}
public static double max(int num1, double num2){
if(num1>num2)
return num1;
else
return num2;
}
public static double max(double num1, int num2){
if(num1>num2)
return num1;
else
return num2;
}
}
Sometimes there may be two or more possible
matches for an invocation of a method, but the
compiler cannot determine the most specific
match. This is referred to as ambiguous
invocation. Ambiguous invocation is a
compilation error.
Variable Scoping
 At a given point, the variables that a statement can access are determined by the scoping rule
 the scope of a variable is the section of a program in which the variable can be accessed (also called visible
or in scope)
 There are two types of scopes in Java
 class scope
 a variable defined in a class but not in any method
 block scope
 a variable defined in a block {} of a method; it is also called a local variable.
Java Scoping Rule
• A variable with a class scope
• class/static variable: a variable defined in class scope and has the static property
• it is associated with the class
• and thus can be accessed (in scope) in all methods in the class
• instance variable: a variable defined in class scope but not static
• it is associated with an instance of an object of the class,
• and thus can be accessed (in scope) only in instance methods, i.e., those non-static methods.
• A variable with a block scope
• can be accessed in the enclosing block; also called local variable
• a local variable can shadow a variable in a class scope with the same name.
• Do not confuse scope with duration
• a variable may exist but is not accessible in a method,
e.g., method A calls method B, then the variables declared in method A exist but are not accessible in B.
• There are can be three types of variables accessible in a method :
• class and instance variables (static and instance variables of the class)
• local variables (those declared in the method)
• formal arguments.
Predicate Methods
• Methods that return Boolean values play an important role in
programming and are called predicate methods.
• the following method returns true if the first argument is divisible by
the second, and false otherwise:
public boolean isDivisibleBy(int x, int y) {
return x % y == 0;}
Once you have defined a predicate method, you can use it just like any other Boolean value. For
example, you can print the integers between 1 and 100 that are divisible by 7 as follows:
for (int i = 1; i <= 100; i++) {
if (isDivisibleBy(i, 7)) {
println(i);
}
}
Controlling Access to Methods
Private
This is the most restrictive access level--private. Only the class in which a private method is defined can call that
method. To declare a private method, use the keyword private. For example, the following class defines one private
method within it:
class Alpha {
private void iamprivate() {
System.out.println("iamprivate"); }
}
Objects of type Alpha can call the iamprivate() method, but objects of other types cannot. For example, the
following class, regardless of which package it is in or its parentage, cannot call the iamprivate() method within the
Alpha class.
class Beta {
void accessMethod() {
Alpha a = new Alpha();
a.iamprivate();}
}
// illegal
You can tell when one of your classes is
attempting to access a method to which it
does not have access--the compiler will print
an error message similar to the following
and refuse to compile your program.
Controlling Access to Methods (Cont..)
Private Protected
The next most restrictive access specified is private protected. This access level includes the private access level
plus allows any of the class's subclasses to call the method. To declare a private protected method, use the
keywords private protected in the method declaration. For example, the following class defines one private
protected method within it:
class Alpha {
private protected void iamprivateprotected() {
System.out.println("iamprivateprotected"); }
}
Objects of type Alpha can call the iamprivateprotected() method. In addition, subclasses of Alpha also have access
to iamprivateprotected(). For instance, this subclass of Alpha, Beta, can call the iamprivateprotected() method of an
Alpha object.
class Beta extends Alpha {
void modifyVariable(Alpha a) {
a.iamprivateprotected();}
}
// legal
Protected
The next access level specifier is protected which allows the class itself, subclasses (with a caveat), and all classes
in the same package to call the method. To declare a protected method, use the keyword protected. For example,
take this version of the Alpha class which is now declared to be within a package named "Greek" and which has a
single protected method declared within it.
package Greek;
class Alpha {
protected void iamprotected() {
System.out.println("iamprotected");
}
}
Now, suppose that the class, Gamma, was also declared to be a member of the Greek package. The Gamma class
can legally call the iamprotected() method declared within the Alpha class because it is within the same package as
Alpha.
package Greek;
class Gamma {
void accessMethod() {
Alpha a = new Alpha();
a.iamprotected();
}}
// legal
Let's introduce a new class, Delta, that derives from Alpha but lives in a different package. The Delta class can
access the iamprotected() method, but only on objects of type Delta or its subclasses. The Delta class cannot call
the iamprotected method on objects of type Alpha. For example, the accessMethod() of the following class
attempts to access the iamprotected() method on an object of type Alpha, which is illegal, and on an object of type
Delta, which is legal.
class Delta extends Alpha {
void accessMethod(Alpha a) {
a.iamprotected = 10;
this.iamprotected = 10;
// illegal
// legal
}
}
If a class is both a subclass of and in the same package as the class with the protected method, then the class has
access to the protected method.
Mechanics of the Method-Calling Process
1.
Java evaluates the argument expressions in the context of the calling method.
2.
Java then copies each argument value into the corresponding parameter variable, which is allocated in a newly
assigned region of memory called a stack frame. This assignment follows the order in which the arguments
appear: the first argument is copied into the first parameter variable, and so on.
3.
Java then evaluates the statements in the method body, using the new stack frame to look up the values of local
variables.
4.
When Java encounters a return statement, it computes the return value and substitutes that value in place of the
call.
5.
Java then discards the stack frame for the called method and returns to the caller, continuing from where it left
off.
Call by value
• In Java the method parameters can be primitive data types or object references. Both are
passed as value only but with a slight difference.
• when primitive data types are passed as method parameters, they are passed by value (a
copy of the value).
public class CallByValue
{
public void display(int y)
{
y = 20;
}
public static void main(String args[])
{
CallByValue cbv = new CallByValue();
int x = 10;
cbv.display(x);
System.out.println(x);
// prints 10 and not 20
}
}
Call by reference
• Incase of object references, the reference is copied (of course, here also a copy only) and passed to
the called method.
• Object reference is passed as a value. So, original reference and the parameter copy both will refer
the same Java object.
• As both refer the same object, if the calling method changes the value of its reference (passed from
calling method), the original object value itself changes.
• It is to Note that object itself is not passed, but it’s references is passed.
• In Java, everyone is passed by value. But with objecct, the value of the reference is passed.
Useful Methods in the Math Class
Math.abs(x)
Returns the absolute value of x
Math.min(x, y)
Returns the smaller of x and y
Math.max(x, y)
Returns the larger of x and y
Math.sqrt(x)
Returns the square root of x
Math.log(x)
Returns the natural logarithm of x (loge x)
Math.exp(x)
Returns the inverse logarithm of x (e x )
Math.pow(x, y)
Returns the value of x raised to the y power (x y )
Math.sin(theta)
Returns the sine of theta, measured in radians
Math.cos(theta)
Returns the cosine of theta
Math.tan(theta)
Returns the tangent of theta
Math.asin(x)
Returns the angle whose sine is x
Math.acos(x)
Returns the angle whose cosine is x
Math.atan(x)
Returns the angle whose tangent is x
Math.toRadians(degrees)
Converts an angle from degrees to radians
Math.toDegrees(radians)
Converts an angle from radians to degrees
Random number generation
import java.lang.Math;
class Rand {
public static void main(String args[])
{
// Generate random number
double rnum = Math.random();
System.out.println("Random Number:" + rnum);
}
}
Download