0% found this document useful (0 votes)
114 views

Lecture - 2 Method Overloading, Inheritance and Method Overridings

Here are a few key reasons for using method overloading in Java: 1. Flexibility - It allows methods to behave differently based on the types and number of arguments passed. This provides flexibility in how methods can be called. 2. Reusability - Method names can be reused for multiple functionalities based on arguments. This improves code reusability by avoiding creation of multiple methods with similar functionality but different names. 3. Readability - Code using overloaded methods is more readable compared to alternatives like optional parameters or method overloading. The signature clearly indicates what the method does. 4. Polymorphism - Method overloading is a way to achieve compile-time polymorphism. The compiler determines which overloaded method
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views

Lecture - 2 Method Overloading, Inheritance and Method Overridings

Here are a few key reasons for using method overloading in Java: 1. Flexibility - It allows methods to behave differently based on the types and number of arguments passed. This provides flexibility in how methods can be called. 2. Reusability - Method names can be reused for multiple functionalities based on arguments. This improves code reusability by avoiding creation of multiple methods with similar functionality but different names. 3. Readability - Code using overloaded methods is more readable compared to alternatives like optional parameters or method overloading. The signature clearly indicates what the method does. 4. Polymorphism - Method overloading is a way to achieve compile-time polymorphism. The compiler determines which overloaded method
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

Method Overloading,

Inheritance & Method


Overriding
Compiled By: Umm-e-Laila & Aneeta Siddiqui

Lecture # 2

1
Course Books

 Text Book:
 Herbert Schildt, Java: The Complete Reference, McGraw-Hill
Education, Eleventh Edition
 Craig Larman, Applying UML & patterns, 2 edition

 Reference Books:
 Cay S. Horstmann, Big Java: Early Objects, Wiley, 7th Edition
 Herbert Schildt, Java: A Beginner's Guide, McGraw-Hill Education,
Eighth Edition

2
Course Instructors

 Umm-e-Laila [email protected]
Assistant Professor, CED
Room Number: BS-04
Tel: 111-994-994, Ext. 536

 Aneeta Siddiqui [email protected]


Assistant Professor, CED
Room Number: BS-03
Tel: 111-994-994,
Course Website

 http://sites.google.com/site/ulaila206

4
Marks Distribution
 Assignments + Quiz______________ 10
 Mid Term ______________ 20
 Lab Work ______________ 20
 Semester Final Paper ______________ 50
 Total Marks ______________ 100

5
Topics Covered
 Method Overloading with example
 Why Method Overloading?
 Constructor Overloading with example
 Method Overriding with example

6
Method Overloading
 A class may define multiple methods with the same
name---this is called method overloading
 usually perform the same task on different data types

 Example: The PrintStream class defines multiple println


methods, i.e., println is overloaded:
println (String s)
println (int i)
println (double d)

 The following lines use the System.out.print method for
different data types:

System.out.println ("The total is:");


double total = 0;
System.out.println (total);
7
Method Overloading

8
Different ways to Overload a method
Three ways to overload a method
In order to overload a method, the argument lists of the
methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
2. Data type of parameters.
For example:
add(int, int)
add(int, float)

9
Different ways to Overload a method
3. Sequence of Data type of parameters.
For example:
add(int, float)
add(float, int)
 In java, Method Overloading is not possible by changing

the return type of the method


 The compiler treats overloaded methods as completely
different methods.
 The compiler knows which one to call based on the
number and the types of the arguments

10
Method Overloading: Signature
 The compiler must be able to determine which
version of the method is being invoked
 This is by analyzing the parameters, which form
the signature of a method
 the signature includes the type and order of the
parameters
 if multiple methods match a method call, the compiler picks
the best match
 if none matches exactly but some implicit conversion can be
done to match a method, then the method is invoke with
implicit conversion.
 the return type of the method is not part of the
signature
11
Method Overloading
Version 1 Version 2

double tryMe (int x) double tryMe (int x, double y)


{ {
return x + .375; return x * y;
} }

Invocation

result = tryMe (25, 4.32)


More Examples
double tryMe ( int x )
{
return x + 5;
Which tryMe will be called?
}
tryMe( 1 );
double tryMe ( double x )
{ tryMe( 1.0 );
return x * .375;
} tryMe( 1.0, 2);

tryMe( 1, 2);
double tryMe (double x, int y)
{ tryMe( 1.0, 2.0);
return x + y;
}
Method Overloading
 Following are a few pointers that we have to
keep in mind while overloading methods in
Java.

 We cannot overload a return type.

 Although we can overload static methods, the


arguments or input parameters have to be
different.

14
Method Overloading

 We cannot overload two methods if they only


differ by a static keyword.

 Like other static methods, the main() method


can also be overloaded.

15
Method Overloading Example
# Example 01

class MotorBike{

private String startMethod = "Kick";

public void start(){


System.out.println(startMethod + " starting ....");
}

public void start(String method){


this.startMethod = method;
System.out.println(startMethod + " starting ....");
}
}

16
Method Overloading Example
# Example 01 cont..

public class DemoApp{


public static void main(String[] arg){
MotorBike motorBike = new MotorBike();
motorBike.start();
motorBike.start("Self");
}
}

/*********************** OUT PUT ****************************/


Kick starting ....
Self starting ....Process finished with exit code 0

17
Method Overloading Example
# Example 02

class Sum
{
int add(int n1, int n2)
{
return n1+n2;
}
int add(int n1, int n2, int n3)
{
return n1+n2+n3;
}
int add(int n1, int n2, int n3, int n4)
{
return n1+n2+n3+n4;
}
int add(int n1, int n2, int n3, int n4, int n5)
{
return n1+n2+n3+n4+n5;
}

18
Method Overloading Example

# Example 02 cont..

public static void main(String args[])


{
Sum obj = new Sum();
System.out.println("Sum of two numbers: "+obj.add(20, 21));
System.out.println("Sum of three numbers: "+obj.add(20, 21, 22));
System.out.println("Sum of four numbers: "+obj.add(20, 21, 22, 23));
System.out.println("Sum of five numbers: "+obj.add(20, 21, 22, 23, 24));
}
}

19
Method Overloading Example

# Example 02 cont..

Output

Sum of two numbers: 41


Sum of three numbers: 63
Sum of four numbers: 86
Sum of five numbers: 110

20
Method Overloading Example

# Example 02 cont..

Output

Sum of two numbers: 41


Sum of three numbers: 63
Sum of four numbers: 86
Sum of five numbers: 110

21
Method Overloading Example
# Example 03: Program to overload static methods in java.

public class Test{


public static int func(int a ){
return 100;
}
public static char func(int a , int b){
return “abc";
}
public static void main(String args[]){
System.out.println(func(1));
System.out.println(func(1,3));
}
}

Output:

100
abc

22
Method Overloading and Type Promotion
Method Overloading and Type Promotion

1. class OverloadingCalculation1{  
2.   void sum(int a,long b)

3. { System.out.println(a+b); }  
4.   void sum(int a,int b,int c)

5. { System.out.println(a+b+c); }  
6.   

7.   public static void main(String args[]){  

8.   OverloadingCalculation1 obj=new OverloadingCalculation1();  

9.   obj.sum(20,20); //now second int literal will be promoted to long  

10.  obj.sum(20,20,20);  

11.    Note: One type is not de-


12.  }   promoted implicitly for
13.}   example double cannot be
de-promoted to any type
implicitly.
Lets see few Valid/invalid cases of method
overloading
 Case 1:
int mymethod(int a, int b, float c)
int mymethod(int var1, int var2, float var3)
Result: Compile time error. Argument lists are exactly same. Both
methods are having same number, data types and same sequence of
data types.
 Case 2:
int mymethod(int a, int b)
int mymethod(float var1, float var2)
Result: Perfectly fine. Valid case of overloading. Here data types of
arguments are different.

25
Lets see few Valid/invalid cases of method
overloading
 Case 3:
int mymethod(int a, int b)
int mymethod(int num)
Result: Perfectly fine. Valid case of overloading. Here number of
arguments are different.

 Case 4:
float mymethod(int a, float b)
float mymethod(float var1, int var2)
Result: Perfectly fine. Valid case of overloading. Sequence of the data
types of parameters are different, first method is having (int, float) and
second is having (float, int).

26
Lets see few Valid/invalid cases of method
overloading
 Case 5:
int mymethod(int a, int b)
float mymethod(int var1, int var2)
Result: Compile time error. Argument lists are exactly same. Even
though return type of methods are different, it is not a valid case. Since
return type of method doesn’t matter while overloading a method.

27
Why Method Overloading ??

 The main advantage of using method


overloading in Java is that it gives us the liberty
to not define a function again and again for
doing the same thing.

28
Constructor Overloading

 In addition to overloading methods, we can also


overload constructors in java.

 Constructor overloading is a concept of having


more than one constructor with different
parameters list, in such a way so that each
constructor performs a different task.

29
Constructor Overloading
 If a class has more than one constructor, they
are “overloaded” and must have different
numbers and/or types of arguments.
 Programmers often provide a “no-args”
constructor that takes no arguments.
 If a programmer does not define any
constructors, Java provides one default no-args
constructor, which allocates memory and sets
fields to the default values
 Overloaded constructor is called based upon the
parameters specified when new is executed.

30
Constructor Overloading

31
Constructor Overloading Example
# Example 01:

class StudentData
{
int stuID;
String stuName;
int stuAge;
StudentData()
{
//Default constructor
stuID = 100;
stuName = "New Student";
stuAge = 18;
}
StudentData(int num1, String str, int num2)
{
//Parameterized constructor
stuID = num1;
stuName = str;
stuAge = num2;
}

32
Constructor Overloading Example
# Example 01 cont…

public static void main(String args[])


{
//This object creation would call the default constructor
StudentData myobj = new StudentData();
System.out.println("Student Name is: "+myobj.StuName);
System.out.println("Student Age is: "+myobj.StuAge);
System.out.println("Student ID is: "+myobj.StuID);

/*This object creation would call the parameterized


* constructor StudentData(int, String, int)*/
StudentData myobj2 = new StudentData(555, "Chaitanya", 25);
System.out.println("Student Name is: "+myobj2.StuName);
System.out.println("Student Age is: "+myobj2.StuAge);
System.out.println("Student ID is: "+myobj2.StuID);
}
}

33
Constructor Overloading Example

# Example 01 cont…

Output:

Student Name is: New Student


Student Age is: 18
Student ID is: 100
Student Name is: Chaitanya
Student Age is: 25
Student ID is: 555

34
This() in Constructor
 One constructor can “call” another constructor in the same
class, but there are special rules
 You call the other constructor with the keyword this
 The call must be the very first thing the constructor does
 Point(int x, int y) {
this.x = x;
this.y = y;
sum = x + y;
}
 Point() {
this(0, 0);
}
 A common reason for overloading constructors is (as
above) to provide default values for missing parameters

35
Role of this() in Constructor
Overloading
# Example 02

public class OverloadingExample2


{
private int rollNum;
OverloadingExample2()
{
rollNum =100;
}
OverloadingExample2(int rnum)
{
this();
/*this() is used for calling the default
* constructor from parameterized constructor.
* It should always be the first statement
* inside constructor body.
*/
rollNum = rollNum+ rnum;
}

36
Role of this() in Constructor
Overloading
# Example 02 cont….

public int getRollNum() {


return rollNum;
}
public void setRollNum(int rollNum) {
this.rollNum = rollNum;
}
public static void main(String args[])
{
OverloadingExample2 obj = new OverloadingExample2(12);
System.out.println(obj.getRollNum());
}
}

37
Role of this() in Constructor
Overloading
# Example 02 cont….

Output :

112

As you can see in the above program that we


called the parameterized constructor during
object creation. Since we have this() placed in
parameterized constructor, the default
constructor got invoked from it and initialized the
variable rollNum.
38
Role of this() in Constructor
Overloading
# Example 03: Guess the output of the following program

public class OverloadingExample2


{
private int rollNum;
OverloadingExample2()
{
rollNum =100;
}
OverloadingExample2(int rnum)
{
rollNum = rollNum+ rnum;
this();
}

39
Role of this() in Constructor
Overloading
# Example 03: Guess the output of the following program

public int getRollNum() {


return rollNum;
}
public void setRollNum(int rollNum) {
this.rollNum = rollNum;
}
public static void main(String args[])
{
OverloadingExample2 obj = new OverloadingExample2(12);
System.out.println(obj.getRollNum());
}
}

40
Role of this() in Constructor
Overloading
# Example 03 cont….

Output :

Exception in thread "main" java.lang.Error: Unresolved compilation


problem:Constructor call must be the first statement in a constructor

Program gave a compilation error.

Reason: this() should be the first statement


inside a constructor..

41
Default Constructor
 If a programmer does not define any
constructors, Java provides one default no-args
constructor, which allocates memory and sets
fields to the default values
class Bird {
int i;}
public class DefaultConstructor {
public static void main(String args[]) {
Bird nc = new Bird(); // default!
}
}
Constructor Overloading
# Example 04
public class Demo
{
int rollNum;
//We are not defining a no-arg constructor here

Demo(int rnum)
{
rollNum = rollNum+ rnum;
}

public static void main(String args[])


{
//This statement would invoke no-arg constructor
Demo obj = new Demo();
}
}

43
Constructor Overloading
# Example 04

Output:

Exception in thread "main" java.lang.Error: Unresolved compilation


problem:The constructor Demo() is undefined

44
COPY CONSTRUCTOR:
 If
Sphere a=b;
b is also of sphere type a therefore a and b points to the
same obj reference. But you will not have distinct
objects.
 For distinct objects use Copy constructor.
Sphere(final Sphere OldSphere)
{
radius = OldSphere.radius; // Set the radius
// Set the coordinates of the center
xCenter = OldSphere. xCenter;
yCenter = OldSphere .yCenter;
zCenter = OldSphere. zCenter;
}
Constructor Overloading
 Another important point to note while
overloading a constructor is:

 When we don’t implement any constructor,


the java compiler inserts the default
constructor into our code during compilation

 However, if we implement any constructor


then compiler doesn’t do it.

46
Why Constructor Overloading ??

 Sometimes there is a need of initializing an


object in different ways.

 This can be done using constructor


overloading.

 For e.g. Vector class has 4 types of


constructors.

47
Why Constructor Overloading ??

 If you do not want to specify the initial capacity


and capacity increment then you can simply
use default constructor of Vector class like this
Vector v = new Vector()
 However, if you need to specify the capacity
and increment then you call the parameterized
constructor of Vector class with two int
arguments like this:
 Vector v= new Vector(10, 5);
48
Inheritance

 Inheritance in java involves a relationship


between parent and child classes.
 The process by which one class acquires the
properties(data members) and
functionalities(methods) of another class is
called inheritance.

49
Inheritance
 The aim of inheritance is to provide the
reusability of code so that a class has to write
only the unique features and rest of the
common properties and functionalities can be
extended from the another class.

50
Inheritance
 Child Class:
 The class that extends the features of another class
is known as child class, sub class or derived class.

 Parent Class:
 The class whose properties and functionalities are
used(inherited) by another class is known as parent
class, super class or Base class.

51
Inheritance
# Example 01
class ParentClass{
//Parent class constructor
ParentClass(){
System.out.println("Constructor of Parent");
}
}
class JavaExample extends ParentClass{
JavaExample(){
/* It by default invokes the constructor of parent class
* You can use super() to call the constructor of parent.
* It should be the first statement in the child class
* constructor, you can also call the parameterized constructor
* of parent class by using super like this: super(10), now
* this will invoke the parameterized constructor of int arg
*/
System.out.println("Constructor of Child");
}
public static void main(String args[]){
//Creating the object of child class
new JavaExample();
}
}

52
Inheritance
# Example 01

Output:

Constructor of Parent
Constructor of Child

53
Advantage of Inheritance
 Inheritance allows us to reuse of code, it
improves reusability in your java application.

 Note: The biggest advantage of Inheritance is


that the code that is already present in base
class need not be rewritten in the child class.

54
Method Overriding
 Inheritance in java involves a relationship
between parent and child classes.
 Whenever both the classes contain methods
with the same name and arguments or
parameters it is certain that one of the methods
will override the other method during execution.
 The method that will be executed depends on
the object.

55
Method Overriding
 If the child class object calls the method, the
child class method will override the parent class
method.
 Otherwise, if the parent class object calls the
method, the parent class method will be
executed.

56
Method Overriding
 Declaring a method in sub class which is
already present in parent class is known as
method overriding.
 Overriding is done so that a child class can give
its own implementation to a method which is
already provided by the parent class.
 In this case the method in parent class is called
overridden method and the method in child
class is called overriding method.

57
Method Overriding
 Conditions for Method Overriding
 Methods of both parent and child class must have
the same name.
 Methods must have the same argument list and
return type.
 A method declared static cannot be overridden.
 If a method cannot be inherited, it cannot be
overridden that is final and static method.
 Constructors cannot be overridden.
 The overriding method cannot be more private than
the method it overrides

58
Method Overriding
# Example 01

class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}

59
Method Overriding
# Example 01

Output:

Boy is eating

60
Method Overriding
# Example 02
 This is called overriding
class Animals{
public void sound(){
a method
System.out.println("This is parent class.");  Method sound in Dog
}
} overrides method
class Dogs extends Animals{ sound in Animal
public void sound(){
System.out.println("Dogs bark");
 A subclass variable can
} shadow a superclass
}
class m{ variable, but a subclass
public static void main(String[] args){ method can override a
Dogs d = new Dogs();
d.sound();
superclass method
}
}

61
Method Overriding
# Example 02 cont..

Output:

Dogs bark

62
Why override a method?
 Dog dog = new Dog();
System.out.println(dog);
 Prints something like Dog@feda4c00
 The println method calls the toString method, which is defined in
Java’s top-level Object class
 Hence, every object can be printed (though it might not look pretty)
 Java’s method public String toString() can be overridden
 If you add to class Dog the following:
 public String toString() {
return name;
}
 Then System.out.println(dog); will print the dog’s name, which may be
something like: Fido

63
More about toString()
 It is almost always a good idea to override
public String toString()
to return something “meaningful” about the object
 When debugging, it helps to be able to print objects
 When you print objects with System.out.print or
System.out.println, they automatically call the objects
toString() method
 When you concatenate an object with a string, the
object’s toString() method is automatically called
 You can explicitly call an object’s toString() method

64
Equality
 Consider these two assignments:
Thing thing1 = new Thing();
Thing thing2 = new Thing();
 Are these two “Things” equal?
 That’s up to the programmer!
 But consider:
Thing thing3 = new Thing();
Thing thing4 = thing3;
 Are these two “Things” equal?
 Yes, because they are the same Thing!

65
The equals method
 Primitives can always be tested for equality with ==
 For objects, == tests whether the two are the same
object
 Two strings "abc" and "abc" may or may not be == !
 Objects can be tested with the method
public boolean equals(Object o)
in java.lang.
 Unless overridden, this method just uses ==
 It is overridden in the class String
 It is not overridden for arrays; == tests if its operands are the
same array
 Morals:
 Never use == to test equality of Strings or arrays or other objects
 Use equals for Strings, java. util.Arrays.equals(a1, a2) for arrays
 If you test your own objects for equality, override equals

66
Calling an overridden method
 When your class overrides an inherited method, it
basically “hides” the inherited method
 Within this class (but not from a different class),
you can still call the overridden method, by
prefixing the call with super.
 Example: super.printEverything();
 You would most likely do this in order to observe
the DRY principle
 The superclass method will do most of the work, but you
add to it or adjust its results
 This isn’t a call to a constructor, and can occur anywhere
in your class (it doesn’t have to be first)

67
Difference between Method Overloading
and Method Overriding
S# Method Overloading Method Overriding
1 Method overloading is used to Method overriding is used to provide the
increase the readability of the program specific implementation of the method that
is already provided by its super class.
2 Method overloading is performed Method overriding occurs in two classes
within class. that have IS-A (inheritance) relationship.
3 In case of method overloading, In case of method overriding, parameter
parameter must be different. must be same.
4 Method overloading is the example of Method overriding is the example of run
compile time polymorphism. time polymorphism.
5 In java, method overloading can't be Return type must be same or covariant in
performed by changing return type of method overriding.
the method only. Return type can be
same or different in method
overloading. But you must have to
change the parameter.
Summary
 You should overload a method when you want to do
essentially the same thing, but with different parameters
 You should override an inherited method if you want to
do something slightly different than in the superclass
 It’s almost always a good idea to override public void

toString() -- it’s handy for debugging, and for many


other reasons
 To test your own objects for equality, override public

void equals(Object o)
 There are special methods (in java.util.Arrays) that

you can use for testing array equality


 You should never intentionally shadow a variable

69

You might also like