Lecture - 2 Method Overloading, Inheritance and Method Overridings
Lecture - 2 Method Overloading, Inheritance and Method Overridings
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
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
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
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
Invocation
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.
14
Method Overloading
15
Method Overloading Example
# Example 01
class MotorBike{
16
Method Overloading Example
# Example 01 cont..
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..
19
Method Overloading Example
# Example 02 cont..
Output
20
Method Overloading Example
# Example 02 cont..
Output
21
Method Overloading Example
# Example 03: Program to overload static methods in java.
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);
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 ??
28
Constructor Overloading
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…
33
Constructor Overloading Example
# Example 01 cont…
Output:
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
36
Role of this() in Constructor
Overloading
# Example 02 cont….
37
Role of this() in Constructor
Overloading
# Example 02 cont….
Output :
112
39
Role of this() in Constructor
Overloading
# Example 03: Guess the output of the following program
40
Role of this() in Constructor
Overloading
# Example 03 cont….
Output :
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;
}
43
Constructor Overloading
# Example 04
Output:
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:
46
Why Constructor Overloading ??
47
Why Constructor Overloading ??
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.
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
void equals(Object o)
There are special methods (in java.util.Arrays) that
69