0% found this document useful (0 votes)
13 views58 pages

Overloading Methods

Uploaded by

shadow.range03
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
0% found this document useful (0 votes)
13 views58 pages

Overloading Methods

Uploaded by

shadow.range03
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 58

MODULE 2

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

 OverloadDemo does not define test(int). Therefore, when test( ) is


called with an integer argument inside Overload, no matching
method is found. However, Java can automatically convert an
integer into a double, and this conversion can be used to resolve
the call. Therefore, after test(int) is not found, Java elevates i to
double and then calls test(double). Of course, if test(int) had been
defined, it would have been called instead. Java will employ its
automatic type conversions only if no exact match is found.

 Method overloading supports polymorphism because it is one way


that Java implements the “one interface, multiple methods”
paradigm.
Advantages of Method Overloading
• Each absolute value method can use the same name. Indeed, Java’s standard class
library includes an absolute value method, called abs( ). This method is overloaded
by Java’s Math class to handle all numeric types. Java determines which version of
abs( ) to call based upon the type of argument.
• overloading can help you manage greater complexity.
• When you overload a method, each version of that method can perform any activity
you desire. There is no rule stating that overloaded methods must relate to one
another. However, from a stylistic point of view, method overloading implies a
relationship. Thus, while you can use the same name to overload unrelated
methods, you should not.
• For example, you could use the name sqr to create methods that return the
square of an integer and the square root of a floating-point value. But these
two operations are fundamentally different.
• Applying method overloading in this manner defeats its original purpose. In
practice, you should only overload closely related operations.
Advantages of Method Overloading
Method overloading improves the Readability and reusability of the program.

Method overloading reduces the complexity of the program.

Using method overloading, programmers can perform a task efficiently and


effectively.
Using method overloading, it is possible to access methods performing related
functions with slightly different arguments and types.
Objects of a class can also be initialized in different ways using the constructors.
Using Objects as Parameters
• In Java, we have only been using simple types as parameters to methods. However, it is both
correct and common to pass objects to methods. For example, consider the following short
program:
Using Objects as Parameters Contd..
output:
ob1 == ob2: true
ob1 == ob3: false

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.

2. call-by-reference: In this approach, 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.

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:

• Each time incrByTen( ) is invoked, a new object is created, and a reference to it is


returned to the calling routine.
• The preceding program makes another important point: Since all objects are
dynamically allocated using new, you don’t need to worry about an object going
out-of-scope because the method in which it was created terminates. The object
will continue to exist as long as there is a reference to it somewhere in your
program. When there are no references to it, the object will be reclaimed the next
time garbage collection takes place.
Recursion
• Recursion is the process of defining something in terms of itself. As it relates to Java
programming, recursion is the attribute that allows a method to call itself. A method that calls
itself is said to be recursive.
• The classic example of recursion is the computation of the factorial of a number.
Recursion
 The factorial of a number N is the product of all the whole numbers between 1 and N. For example, 3
factorial is 1 × 2 × 3 ×, or 6. Here is how a factorial can be computed by use of a recursive method:
 Output : Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

 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 .

Access within class within outside outside


Modifier package package by package
subclass
only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Understanding Static
 The static keyword is a non-access modifier used for methods and attributes. Static
methods/attributes can be accessed without creating an object of a class.
 The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than
an instance of the class.

 The static can be:


1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
Java static variable
 If you declare any variable as static, it is known as a static variable.
o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
 Advantages of static variable

• It makes your program memory efficient (i.e., it saves memory).

 Understanding the problem without static variable


class Student{
int rollno;
String name;
String college=“ENG";
}
Java static variable Contd…
• Suppose there are 500 students in my college, now all instance data members will get memory each time when the
object is created. All students have its unique rollno and name, so instance data member is good in such case. Here,
"college" refers to the common property of all objects. If we make it static, this field will get the memory only once.
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college =“ENG"; //static variable

//constructor
Student(int r, String n){
rollno = r;
name = n;
}

//method to display the values


void display (){
System.out.println(rollno+" "+name+" "+college);
}
}
Java static variable Contd…

//Java Program to demonstrate the use of static variable


//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(24,“Avani");
Student s2 = new Student(26,“Inchara");
//we can change the college of all objects by the single line of code
//Student.college=“BIET";
s1.display();
s2.display();
}
}
Output:
24 Avani ENG
26 Inchara ENG
Java static method
If you apply static keyword with any method, it is known as static
method.
1. A static method belongs to the class rather than the object of a class.
2. A static method can be invoked without the need for creating an instance of
a class.
3. A static method can access static data member and can change the value of
it.

Restrictions for the static method


There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static
method directly.
2. this and super cannot be used in static context.
Example of static method
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = “Engineering";

//static method to change the value of static variable


static void change(){
college = "BIET";
}

//constructor to initialize the variable


Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);
}
}
Example of static method Contd…
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change(); //calling change method
//creating objects
Student s1 = new Student(24,“Avani”);
Student s2 = new Student(26,“Inchara");
Student s3 = new Student(48,“Rinith");

//calling display method


s1.display();
s2.display();
s3.display();
}
}
Example of static method Contd…
Output: 24 Avani BIET
26 Inchara BIET
48 Rinith BIET
BUILD SUCCESSFUL (total time: 0 seconds)

 The static method can not use non static data member or call non-static method directly.

class A{
int a=40;//non static

public static void main(String args[]){


System.out.println(a);
}
}

Output: Compile Time Error


Java static block
 Java static block
 Is used to initialize the static data member.
 It is executed before the main method at the time of class loading.

 Example of static block


class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}

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

//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);
}
}
Demonstrate static variables, methods, and blocks.
With Simple Program Contd..

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;

static void callme() {


System .out .println ("a =" + a);
}
}
class StaticByName {
public static void main (String[] args) {

StaticDemo .callme ();


System .out .println ("b =" + StaticDemo .b);
}
}
Output:
a =42
b =99
Java final keyword
 A field can be declared as final. Doing so prevents its contents from being modified, making it,
essentially, a constant.
 Initialize a final field when it is declared. There are two ways:
 First, you can give it a value when it is declared.
 Second, you can assign it a value within a constructor.
 Here is an example:
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;
 It is a common coding convention to choose all uppercase identifiers for final fields.
 Both method parameters and local variables can be declared final.
 Declaring a parameter final prevents it from being changed within the method.
 Declaring a local variable final prevents it from being assigned a value more than once.
 The keyword final can also be applied to methods, but its meaning is substantially different than
when it is applied to variables.
Definition and Usage final keyword
The final keyword is a non-access modifier used for classes, attributes
and methods, which makes them non-changeable (impossible to inherit or
override).

The final keyword is useful when you want a variable to always store
the same value, like PI (3.14159...).

The final keyword is called a "modifier".

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.

 Example of final method


class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


void run(){System.out.println("running safely with 100kmph");}

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}
Java final class

 If you make any class as final, you cannot extend it.

 Example of final class

final class Bike{}

class Honda1 extends Bike{


void run(){
System.out.println("running safely with 100kmph");
}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}

Output: Compile Time Error


Java final keyword
The final keyword can be applied with the variables,
a final variable that have no value it is called blank final variable or uninitialized
final variable.
It can be initialized in the constructor only.
The blank final variable can be static also which will be initialized in the static
block only.
Java final keyword
 Q) What is blank or uninitialized final variable?

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);
}

public static void main(String args[]){


new Bike10();
}
}
Output: 70
static blank final variable
 A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.

 Example of static blank final variable


class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
Java final keyword

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.
Q) Can we declare a constructor final?

No, because constructor is never inherited.


Introducing Nested and Inner Classes

 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 ();
}

//this is an inner class


class Inner {
void display() {
System.out .println ("display : outer x = " + outer_x);
}
}
}
program illustrates how to define and use an inner
class Contd..
class InnerClassDemo {
public static void main (String[] args) {
Outer outer = new Outer();
outer .test(); }
}
Output: display: outer_x = 100
Explanation:
 An inner class named Inner is defined within the scope of class Outer.
 Therefore, any code in class Inner can directly access the variable outer_x.
 An instance method named display( ) is defined inside Inner. This method displays outer_x
on the standard output stream.
 The main( ) method of InnerClassDemo creates an instance of class Outer and invokes its
test( ) method. That method creates an instance of class Inner and the display( ) method is
called.
program illustrates how to define and use an inner class
Contd..
 It is important to realize that an instance of Inner can be created
only in the context of class Outer. The Java compiler generates
an error message otherwise. In general, an inner class instance is
often created by code within its enclosing scope, as the example
does.
 As explained, an inner class has access to all of the members of
its enclosing class, but the reverse is not true.
 Members of the inner class are known only within the scope of
the inner class and may not be used by the outer class. For
example,
Simple Program defining an inner class within a for loop
Simple Program defining an inner class within a for loop
 The output from this version of the program is shown here:
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
 While nested classes are not applicable to all situations,
they are particularly helpful when handling events.

You might also like