Overloading Methods
Overloading Methods
Overloading Methods
Objects as Parameters
Argument Passing
Returning Objects
Recursion
Access Control
Understanding static
Introducing final
Introducing Nested and Inner Classes.
Overloading Methods
• In Java, 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,
methods are said to be overloaded, and the process is referred to as method
overloading.
Method overloading is one of the ways that Java supports polymorphism.
One of Java’s most exciting and useful features.
When an overloaded 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.
When Java encounters a call to an overloaded method, it simply executes the
version of the method whose parameters match the arguments used in the call.
Simple example that illustrates method overloading:
Simple example that illustrates method overloading:
Contd..
Output:
No parameters a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Simple example that illustrates method overloading:
Contd..
Explanation:
test( ) is overloaded four times.
The first version takes no parameters,
the second takes one integer parameter,
the third takes two integer parameters, and
the fourth takes one double parameter. The fact that fourth version of test( ) also returns a
value is of no consequence relative to overloading, since return types do not play a role in
overload resolution.
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. In
some cases, Java’s automatic type conversions can play a role in overload resolution.
Automatic type conversions apply to overloading
Automatic type conversions apply to overloading Contd…
Output:
No parameters
a and b: 10 20
Inside test(double) a: 88 Inside
test(double) a: 123.2
Explanation:
the equalTo( ) method inside Test compares two objects for equality and returns the result.
That is, it compares the invoking object with the one that it is passed.
If they contain the same values, then the method returns true. Otherwise, it returns false.
Notice that the parameter o in equalTo( ) specifies Test as its type. Although Test is a class
type created by the program, it is used in just the same way as Java’s built-in types.
One of the most common uses of object parameters involves constructors.
A Closer Look at Argument Passing
There are two ways of passing an argument to a subroutine.
1. call-by-value: This approach 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.
Note: Java uses call-by-value to pass all arguments, the precise effect differs between whether a
primitive type or a reference type is passed.
consider the following program (call-by-value)
• call-by-value: When you pass a primitive type to a method, it is passed by value. Thus, a copy of the
argument is made, and what occurs to the parameter that receives the argument has no effect outside the
method. For example, consider the following program:
consider the following program (call-by-value) Contd..
Output
a and b before call: 15 20
a and b after call: 15 20
Explanation:
1. the operations that occur inside meth( ) have no effect on the values of a and b
used in the call; their values here did not change to 30 and 10.
call-by-reference
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 create a variable of a class type, you are only creating a reference to an object. Thus,
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.
The objects act as if they are passed to methods by use of call-by-reference.
Changes to the object inside the method do affect the object used as an argument.
consider the following program (call-by-reference)
consider the following program (call-by-reference) Contd..
Output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
As you can see, in this case, the actions inside meth( ) have affected
the object used as an argument.
Note: When an object reference is passed to a method, reference itself
is passed by use of call-by-value. However, since the value being
passed refers to an object, the copy of that value will still refer to the
same object that its corresponding argument does.
Returning Objects
A method can return any type of data, including class types that you create. For example, in the following
program, the incrByTen( ) method returns an object in which the value of a is ten greater than it is in the
invoking object.
Returning Objects Contd..
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
Explanation:
Explanation:
Here is how it works. When fact( ) is called with an argument of 1, the function returns 1;
otherwise, it returns the product of fact(n–1)*n. To evaluate this expression, fact( ) is called with
n–1. This process repeats until n equals 1 and the calls to the method begin returning.W
When you compute factorial of 3, the first call to fact( ) will cause a second call to be made with
an argument of 2. This invocation will cause fact( ) to be called a third time with an argument of
1. This call will return 1, which is then multiplied by 2 (the value of n in the second invocation).
This result (which is 2) is then returned to the original invocation of fact( ) and multiplied by 3
(the original value of n). This yields the answer,6. You might find it interesting to insert
println( ) statements into fact( ), which will show at what level each call is and what the
intermediate answers are.
Introducing Access Control
Encapsulation links data with the code that manipulates it. However, encapsulation provides
another important attribute: access control. Through encapsulation, you can control what parts of
a program can access the members of a class. By controlling access, you can prevent misuse.
How a member can be accessed is determined by the access modifier attached to its
declaration. Java supplies a rich set of access modifiers. Some aspects of access control are
related mostly to inheritance or packages. (A package is, essentially, a grouping of classes.)
Java’s access modifiers are public, private, and protected. Java also defines a default access
level. protected applies only when inheritance is involved. The other access modifiers are
described next.
When a member of a class is modified by public, then that member can be accessed by any
other code.
When a member of a class is specified as private, then that member can only be accessed by
other members of its class.
Now you can understand why main() has always been preceded by the public modifier. It is
called by code that is outside the program—that is, by the Java run-time system.
When no access modifier is used, then by default the member of a class is public within its own
package, but cannot be accessed outside of its package
Access Control
There are two types of modifiers in Java:
access modifiers and
non-access modifiers.
Introducing Access Control
There are four types of Java access modifiers:
1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
5. There are many non-access modifiers, such as static, abstract, synchronized,
native, volatile, transient, etc. Here, we are going to learn the access modifiers
only.
Understanding Java Access Modifiers
Let's understand the access modifiers in Java by a simple table .
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
The static method can not use non static data member or call non-static method directly.
class A{
int a=40;//non static
Output:
static block is invoked
Hello main
Questions
Q) Why is the Java main method static?
Ans) It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the problem of
extra memory allocation.
Q) Can we execute a program without main() method?
Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK
1.7, it is not possible to execute a Java class without the main method.
Static Keyword
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( ). main( ) is
declared as static because it must be called before any objects exist.
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 directly call other static methods of their class.
They can only directly access static variables of their class.
They cannot refer to this or super in any way. (The keyword super relates to inheritance and is described in
the next chapter.)
If you need to do computation in order to initialize your static variables, you can declare a
static block that gets executed exactly once, when the class is first loaded. The following
example shows a class that has a static method, some static variables, and a static
initialization block:
Demonstrate static variables, methods, and blocks. With Simple Program
static {
System .out .println ("Static block initialized.");
b = a*4;
}
Output:
Static block initialized.
x =42
a=3
b = 12
BUILD SUCCESSFUL (total time: 0 seconds)
Demonstrate static variables, methods, and blocks.
With Simple Program Contd..
Explanation:
As soon as the UseStatic class is loaded, all of the static statements are run.
First, a is set to 3, then the static block executes, which prints a message and then
initializes b to a*4 or 12. Then main( ) is called, which calls meth( ), passing 42 to x.
The three println( ) statements refer to the two static variables a and b, as well as to the
parameter x.
static methods and variables can be used independently of
any object
Outside the class in which they are defined, static methods and variables can be used
independently of any object. 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( )
Here, classname is the name of the class in which the static method is declared. As you can
see, this format is similar to that used to call non-static methods through object-reference
variables. A static variable can be accessed in the same way—by use of the dot operator on
the name of the class. This is how Java implements a controlled version of global methods
and global variables.
1. Here is an example. Inside main( ), the static method callme( ) and the
2. static variable b are accessed through their class name StaticDemo.
Static Variable accessed through their class name
class StaticDemo {
static int a = 42;
static int b =99;
The final keyword is useful when you want a variable to always store
the same value, like PI (3.14159...).
The java final keyword can be used in many context. Final can be:
1. variable
2. method
3. class
Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable: There is a final variable speedlimit, we are going to change the value of
this variable, but It can't be changed because final variable once assigned a value can never be
changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output: Compile Time Error
Java final method
If you make any method as final, you cannot override it.
1. A final variable that is not initialized at the time of declaration is known as blank final
variable.
2. If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.
3. It can be initialized only in constructor.
Example of blank final variable
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
Initialize blank final variable
Q) Can we initialize blank final variable?
Yes, but only in constructor. For example:
class Bike10{
final int speedlimit;//blank final variable
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
If you declare any parameter as final, you cannot change the value of it.
Q) Can we declare a constructor final?
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. Thus, if class B is
defined within class A, then B does not exist independently of A.
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.
A nested class that is declared directly within its enclosing class scope is a member of its
enclosing class.
It is also possible to declare a nested class that is local to a block
There are two types of nested classes:
1. static and
2. non-static.
A static nested class is one that has the static modifier applied. Because it is static, it must
access the non-static members of its enclosing class through an object. That is, it cannot refer
to non-static members of its enclosing class directly. Because of this restriction, static nested
classes are seldom used.
Introducing Nested and Inner Classes Contd..
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.
The class named Outer has one instance variable named outer_x, one instance
method named test( ), and defines one inner class called Inner.
program illustrates how to define and use an inner class.
program illustrates how to define and use an inner
class Contd..
/ /Demonstrate an inner class.
class Outer {
int outer_x = 100;
void test () {
Inner inner = new Inner(); inner .display ();
}