SlideShare a Scribd company logo
Inheritance
Inheritance
Inheritance
• All of the classes have common attributes (Age, Height, Weight) and methods (Walk,
Talk, Eat).
• However, they have some special skills like Diagnose, Playfootball and Runbusiness.
• In each of the classes, you would be copying the same code for Walk, Talk and Eat for
each character.
Attributes:
Age, Height, Weight
Methods:
Talk()
Walk()
Eat()
Diagnose()
class Doctor
Attributes:
Age, Height, Weight
Methods:
Talk()
Walk()
Eat()
Playfootball()
class Footballer
Attributes:
Age, Height, Weight
Methods:
Talk()
Walk()
Eat()
Runbusiness()
class Businessman
Inheritance
• The mechanism of a class to derive properties and
characteristics from another class is called Inheritance.
• It is the most important feature of Object Oriented
Programming.
• Inheritance is the process, by which class can
acquire(reuse) the properties and methods of another
class.
• Base Class: The class whose properties are inherited by sub
class is called Base Class/Super class/Parent class.
• Derived Class: The class that inherits properties from
another class is called Sub class/Derived Class/Child class.
• Inheritance is implemented using super class and sub class
relationship in object-oriented languages.
Base Class
Derived Class
Inheritance
Methods:
Diagnose()
class Doctor
Methods:
Playfootball()
class Footballer
Methods:
Runbusiness()
class Businessman
Attributes:
Age, Height, Weight
Methods:
Talk() , Walk(), Eat()
class Person
class Person
is called
Base class
These classes
are called
Derived class
Inheritance
Attributes:
Private_vehicle
class Car
Attributes:
Public_vehicle
class Bus
Attributes:
Goods_vehicle
class Truck
Attributes:
Engine_no, color
Methods:
apply_breaks()
class Vehicle
Inheritance: Advantages
• Promotes reusability
• When an existing code is reused, it leads to less
development and maintenance costs.
• It is used to generate more dominant
objects.
• Avoids duplicity and data redundancy.
• Inheritance makes the sub classes follow a
standard interface.
Base Class
Derived Class
Implementing Inheritance
• Subclass-Superclass Relationship
Introduction
• Inheritance is the process, by which a class can acquire(reuse) the properties
and methods of another class.
• The mechanism of deriving a new class from an old class is called inheritance.
• The new class is called derived class and old class is called base class.
• The derived class may have all the features of the base class and the
programmer can add new features to the derived class.
• Inheritance is also known as “IS-A relationship” between parent and child
classes.
• For Example :
• Car IS A Vehicle
• Bike IS A Vehicle
• EngineeringCollege IS A College
• MedicalCollege IS A College
• MCACollege IS A College
Inheritance Example
Attributes:
privatevehicle
class Car
Attributes:
publicvehicle
class Bus
Attributes:
goodsvehicle
class Truck
Attributes:
Engineno, color
Methods:
applybreaks()
class Vehicle
How to implement Inheritance in java
• To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.
Syntax:
class subclass-name extends superclass-name
{
// body of class…
}
Implementing Inheritance in java
Class A
Base Class
Class B
Derived Class
class A
{
//SuperClass or ParentClass or BaseClass
}
class B extends A
{
//SubClass or ChildClass or DerivedClass
}
the keyword “extends” is used to create a subclass of A
Implementing Inheritance in java
1. class Person
2. {
3. String name;
4. long contact;
5. }
6. class Employee extends Person
7. {
8. int empID;
9. String designation;
10.}
11.Class Customer extends Person
12.{
13. int customerID;
14. int invoiceNo;
15.}
Person
name:String
Contact:long
Employee
empID:int
Designation:Strin
g
Customer
customerID:int
InvoiceNo:int
Implementing Inheritance in java
1. class Person
2. {
3. String name;
4. long contact;
5. public void dispContact()
6. { System.out.println(“num=”+contact);
7. }
8. }
9. class Employee extends Person
10.{
11. int empID;
12. String designation;
13.}
14.Class Customer extends Person
15.{
16. int customerID;
17. int invoiceNo;
18.}
Person
name:String
Contact:long
dispContact():void
Employee
empID:int
Designation:Strin
g
Customer
customerID:int
InvoiceNo:int
Property of Inheritance
Property of Inheritance
Class A
Base Class
Class B
Derived Class Derived Class B can access attributes
and methods of Base class A
Base class A can’t access attributes
and methods of Derived Class B
Derived Class B can’t access
private members of Base class A
A class member that has been declared as
private will remain private to its class. It is not
accessible by any code outside its class,
including subclasses.
Inheritance by Example
Example1: InheritanceDemo1
A
#i:int
~j:int
showij():void
B
~k:int
showk():void
add():void
Example1: InheritanceDemo.java
1. class A{
2. protected int i;
3. int j;
4. void showij(){
5. System.out.println("i="+i+" j="+j);
6. }
7. }
8. class B extends A{ //inheritance
9. int k;
10. void showk(){
11. System.out.println("k="+k);
12. }
13. void add(){
System.out.println("i+j+k="+(i+j+k));
14. }
15.}
16.class InheritanceDemo{
17.public static void main(String[]
args)
18. {
19. A superObjA= new A();
20. superObjA.i=10;
21. superObjA.j=20;
22. B subObjB= new B();
23. subObjB.k=30;
24. superObjA.showij();
25. subObjB.showk();
26. subObjB.add();
27. }
28.} i=10 j=20
k=30
i+j+k=30
Outpu
t
Types of Inheritance in Java
A
B
1. Single Inheritance
A
B
C
3. Multilevel Inheritance
A
C
B
2. Hierarchical Inheritance
A B
C
4. Multiple Inheritance
A
C
B
D
5. Hybrid Inheritance
Note: Multiple and Hybrid
Inheritance is not supported in Java
with the Class Inheritance, we can
still use those Inheritance with
Interface which we will learn in later
part of the Unit
Single Inheritance A
B
Single Inheritance: InheritanceDemo.java
1. class A{
2. protected int i;
3. int j;
4. void showij(){
5. System.out.println("i="+i+" j="+j);
6. }
7. }
8. class B extends A{ //inheritance
9. int k;
10. void showk(){
11. System.out.println("k="+k);
12. }
13. void add(){
System.out.println("i+j+k="+(i+j+k));
14. }
15.}
16.class InheritanceDemo{
17.public static void main(String[]
args)
18. {
19. A superObjA= new A();
20. superObjA.i=10;
21. superObjA.j=20;
22. B subObjB= new B();
23. subObjB.i=100
24. subObjB.j=100;
25. subObjB.k=30;
26. superObjA.showij();
27. subObjB.showk();
28. subObjB.add();
29. }
30.}
i=10 j=20
k=30
i+j+k=230
Outpu
t
A
B
Hierarchical Inheritance A
C
B
OOP Java is the easiest, scoring and my favorite subject
1. class A{
2. protected int i;
3. int j;
4. void showij(){
5. System.out.println("inside
class A:i="+i+" j="+j);
6. }
7. }
8. class B extends A{
9. int k;
10. void showk(){
System.out.println("inside
class B:k="+k);
11. }
12. void add_ijk(){
System.out.println(i+"+"+j+"+"+
k+"="+(i+j+k));
13. }}
14.class C extends A{
15. int m;
16. void showm(){
17. System.out.println("inside
class C:k="+m);
18. }
19. void add_ijm(){
20. System.out.println(i+"+"+j+
"+"+m+"="+(i+j+m));
21. }
22.}
InheritanceLevel.java
A
C
B
OOP Java is the easiest, scoring and my favorite subject
23.class InheritanceLevel{
24. public static void main(String[] args) {
25. A superObjA= new A();
26. superObjA.i=10;
27. superObjA.j=20;
28. superObjA.showij();
29. B subObjB= new B();
30. subObjB.i=100;
31. subObjB.j=200;
32. subObjB.k=300;
33. subObjB.showk();
34. subObjB.add_ijk();
35. C subObjC= new C();
36. subObjC.i=1000;
37. subObjC.j=2000;;
38. subObjC.m=3000;
39. subObjC.showm();
40. subObjC.add_ijm();
41. }
42.}
inside class A:i=10 j=20
inside class B:k=300
100+200+300=600
inside class C:k=3000
1000+2000+3000=6000
Outpu
t
A
C
B
InheritanceLevel.java
Multilevel Inheritance
A
B
C
OOP Java is the easiest, scoring and my favorite subject
1. class A{
2. protected int i;
3. int j;
4. void showij(){
5. System.out.println("inside
class A:i="+i+" j="+j);
6. }
7. }
8. class B extends A{
9. int k;
10. void showk(){
System.out.println("inside
class B:k="+k);
11. }
12. void add_ijk(){
System.out.println(i+"+"+j+"+"+
k+"="+(i+j+k));
13. }}
14.class C extends B{
15. int m;
16. void showm(){
17. System.out.println("inside
class C:k="+m);
18. }
19. void add_ijkm(){
20. System.out.println(i+"+"+j+
"+"+k+"+"+m+"="+(i+j+k+m));
21. }
22.}
InheritanceMultilevel.java
A
B
C
OOP Java is the easiest, scoring and my favorite subject
23.class InheritanceMultilevel{
24. public static void main(String[] args) {
25. A superObjA= new A();
26. superObjA.i=10;
27. superObjA.j=20;
28. superObjA.showij();
29. B subObjB= new B();
30. subObjB.i=100;
31. subObjB.j=200;
32. subObjB.k=300;
33. subObjB.showk();
34. subObjB.add_ijk();
35. C subObjC= new C();
36. subObjC.i=1000;
37. subObjC.j=2000;
38. subObjC.k=3000;
39. subObjC.m=4000;
40. subObjC.showm();
41. subObjC.add_ijkm();
42. }
inside class A:i=10 j=20
inside class B:k=300
100+200+300=600
inside class C:k=4000
1000+2000+3000+4000=10000
Outpu
t
A
B
C
InheritanceMultilevel.java
Derived Class with Constructor
Derived Class with Constructor
Cube
# height: double
# width: double
# depth: double
Cube()
volume(): double
CubeWeight
# weigth: double
CubeWeight(double, double, double,
double):double
CubeInherit
cw1:CubeWeight
cw2:CubeWeight
main(): void
OOP Java is the easiest, scoring and my favorite subject
1. class Cube{
2. protected double
height,width,depth;
3. Cube(){
4. System.out.println("inside
5. default Constructor:CUBE");
6. }
7. double volume(){
8. return height*width*depth;
9. }
10.}
11.class CubeWeight extends Cube{
12.double weigth;
13.CubeWeight(double h,double w,double d, double m)
14.{
15. System.out.println("inside Constructor:
16. CUBEWEIGTH");
17. height=h;
18. width=w;
19. depth=d;
20. weigth=m;
21. }}
22.class CubeInherit{
23. public static void main(String[] args) {
24.CubeWeight cw1= new
25. CubeWeight(10,10,10,20.5);
26.CubeWeight cw2= new
27. CubeWeight(100,100,100,200.5);
28.System.out.println("cw1.volume()="
+cw1.volume());
29.System.out.println("cw2.volume()="
+cw2.volume());
30. }}
CubeInherit.java
inside default Constructor:CUBE
inside Constructor:CUBEWEIGTH
inside default Constructor:CUBE
inside Constructor:CUBEWEIGTH
cw1.volume()=1000.0
cw2.volume()=1000000.0
Outpu
t
Super Keyword
Super Keyword
• Whenever a subclass needs to refer to its immediate superclass, it can do so by
use of the keyword super. Super has two general forms:
1. Calls the superclass constructor.
2. Used to access a members(i.e. instance variable or method) of the superclass.
Using super to Call Superclass Constructors
• Call to super must be first statement in constructor
Cube
# height: double
# width: double
# depth: double
volume(): double
CubeWeight
# weigth: double
CubeInherit
cw1:CubeWeight
cw2:CubeWeight
main(): void
Using “super”
Cube(double, double, double)
CubeWeight(double, double, double, double)
OOP Java is the easiest, scoring and my favorite subject
1. class Cube{
2. protected double
height,width,depth;
3. Cube(double h,double w,double d){
4. System.out.println("Constructor:
5. CUBE");
6. height=h;
7. width=w;
8. depth=d;
9. }
10. double volume(){
11. return height*width*depth;
12. }
13.}
14.class CubeWeight extends Cube{
15. double weigth;
16. CubeWeight(double h,double w,double d, double m){
17. super(h,w,d); //call superclassConstructor
18. System.out.println("Constructor:CUBEWEIGTH");
19. weigth=m;
20. }
21.}
22. class CubeInheritSuper{
23. public static void main(String[] args) {
24. CubeWeight cw1= new
CubeWeight(10,10,10,20.5);
25. CubeWeight cw2= new
CubeWeight(100,100,100,200.5);
26. System.out.println("cw1.volume()="+cw1.volume());
27. System.out.println("cw1.weigth="+cw1.weigth);
28. System.out.println("cw2.volume()="+cw2.volume());
29. System.out.println("cw2.weigth="+cw2.weigth);
30. }
31. }
CubeInheritSuper.java
Constructor:CUBE
Constructor:CUBEWEIGTH
Constructor:CUBE
Constructor:CUBEWEIGTH
cw1.volume()=1000.0
cw1.weigth=20.5
cw2.volume()=1000000.0
cw2.weigth=200.5
Outpu
t
Using super to Call Superclass Constructors
Using super to access members
• The second form of super acts somewhat like this, except that it always refers
to the superclass of the subclass in which it is used.
• Syntax:
• This second form of super is most applicable to situations in which member
names of a subclass hide members by the same name in the superclass.
super.member
member can be either a
method or an instance
variable.
Using super to access members: SuperMemberDemo.java
1. class A{
2.
3. }
4. class B extends A{
5. int i,k;
6. B(int a,int b){
7.
8. this.i=b;
9. }
10. void show(){
11. System.out.println("super.i="+super.i);
12. System.out.println("this.i="+this.i);
13. }
14.}
15.class SuperMemberDemo{
16. public static void main(String[]
args)
17. {
18. B b= new B(12,56);
19. b.show();
20. }
21.}
super.i=12
this.i=56
Outpu
t
super.i=a;
int i;
Using super to access members: SuperMemberDemo.java
1. class A{
2. int i=33;
3. void show(){
4. System.out.println("inside A:i="+i);
5. }
6. }
7. class B extends A{
8. int i,k;
9. B(int a,int b){
10. super.show();
11. super.i=a;
12. this.i=b;
13. }
14. void show(){
15. System.out.println("super.i="+super.i);
16. System.out.println("this.i="+this.i);
17. }
18.}
19.class SuperMemberDemo{
20. public static void
main(String[] args)
21. {
22. B b= new B(12,56);
23. b.show();
24. }
25.}
inside A:i=33
super.i=12
B.i=56
Outpu
t
Points to remember for super
• When a subclass calls super( ), it is calling the constructor of its immediate
superclass.
• This is true even in a multileveled hierarchy.
• super( ) must always be the first statement executed inside a subclass
constructor.
• If a constructor does not explicitly call a superclass constructor, the Java
compiler automatically inserts a call to the no-argument constructor of the
superclass.
• The most common application of super keyword is to eliminate the ambiguity
between members of superclass and sub class.
Why Inheritance
1. Reusability of code
2. To implement polymorphism at run time (method overriding).
Class A
Base Class
Class B
Derived Class
Access Control
Access Control
Access Modifier Description
Private(-) The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
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.
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.
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.
Access Control
Access
Modifier
Same Class Same Package Sub Class Universal
Private
Default
Protected
Public
Exercise
1. Why multiple and Hybrid inheritance is not supported in java.
2. Implement inheritance in java using following diagram.
Shape
#String name
+ String color
Shape()
Circle
~ radius: double
~PI: double
calCircleArea(): double
Rectangle
~height: double
~width: double
calRectArea(): double
Triangle
~length: double
~width: double
calTriArea(): double
Interview Questions
1. Which class in Java is superclass of every other class?
2. Can a class extend itself?
3. Can we assign superclass to subclass?
4. Can a class extend more than one class?
Polymorphism
Polymorphism
Polymorphism: It is a Greek term means, “One name many Forms”
Polymorphism
Poly:
Many
Morphism:
Types
 Most important concept of object
oriented programming
 In OOP, Polymorphism is the ability of an
object to take on many forms.
Polymorphism
• Polymorphism is the method in an object-oriented programming language that
does different things depending on the class of the object which calls it.
• Polymorphism can be implemented using the concept of overloading and
overriding.
Polymorphism: Advantages
• Single variable can be used to store multiple
data types.
• Easy to debug the codes.
• It allows to perform a single act in different
ways.
• Polymorphism allows the object to decide
which form of the function to implement at
compile-time (overloading) as well as run-
time (overriding).
• Reduces coupling, increases reusability and
makes code easier to read.
Implementing Polymorphism
Polymorphism
Using
Method
Overloading
Using
Method Overriding
Implementing Polymorphism
• Overloading & Overrding
Implementing Polymorphism
Polymorphism
Using
Method
Overloading
Using
Method Overriding
Method Overloading
Method Overloading: Compile-time Polymorphism
• Definition: When two or more methods are implemented that share same name but
different parameter(s), the methods are said to be overloaded, and the process is
referred to as method overloading
• Method overloading is one of the ways that Java implements polymorphism.
• 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.
• E.g. public void draw()
public void draw(int height, int width)
public void draw(int radius)
• Thus, overloaded methods must differ in the type and/or number of their parameters.
• While in overloaded methods with different return types and same name &
parameter are not allowed ,as the return type alone is insufficient for the compiler to
distinguish two versions of a method.
Method Overloading: Compile-time Polymorphism
1. class Addition{
2. int i,j,k;
3. void add(int a){
4. i=a;
5. System.out.println("add i="+i);
6. }
7. void add(int a,int b){overloaded add()
8. i=a;
9. j=b;
10. System.out.println("add i+j="+(i+j));
11. }
12. void add(int a,int b,int c){overloaded add()
13. i=a;
14. j=b;
15. k=c;
16. System.out.println("add i+j+k="+(i+j+k));
17. }
18.}
19.class OverloadDemo{
20.public static void
main(String[] args){
21. Addition a1= new Addition();
22. //call all versions of add()
23. a1.add(20);
24. a1.add(30,50);
25. a1.add(10,30,60);
26. }
27.}
add i=20
add i+j=80
add i+j+k=100
Outpu
t
Method Overriding
Method Overriding: Run-time Polymorphism
• In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said
to override the method in the superclass.
• Definition: If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
Method Overriding: OverrideDemo.java
1. class Shape{
2. void draw(){
3. System.out.println("Draw
Shape");
4. }
5. }
6. class Circle extends Shape{
7. void draw(){
8. System.out.println("Draw
Circle");
9. }
10.}
11.class Square extends Shape{
12. void draw(){
13. System.out.println("Draw
Square");
14. }
15.}
1. class OverrideDemo{
2. public static void
main(String[] args) {
3. Circle c= new Circle();
4. c.draw(); //child class meth()
5. Square sq= new Square();
6. sq.draw();//child class meth()
7. Shape sh= new Shape();
8. sh.draw();//parentClass meth()
9. }
10.}
Draw Circle
Draw Square
Draw Shape
Outpu
t
When an overridden method is called from
within a subclass, it will always refer to the
version of that method defined by the
subclass. The version of the method
defined by the superclass will be hidden.
Method Overriding: OverrideDemo.java
1. class Shape{
2. void draw(){
3. System.out.println("Draw
Shape");
4. }
5. }
6. class Circle extends Shape{
7. void draw(){
8.
9. System.out.println("Draw
Circle");
10. }
11.}
12.class Square extends Shape{
13. void draw(){
14. System.out.println("Draw
Square");
15. }
16.}
1. class OverrideDemo{
2. public static void
main(String[] args) {
3. Circle c= new Circle();
4. c.draw();
5. Square sq= new Square();
6. sq.draw();
7. }
8. }
Draw Shape
Draw Circle
Draw Square
Outpu
t
super.draw();
Here, super.draw( ) calls the superclass version of
draw( ).
Overridden methods in Java are similar to virtual functions in C++ and C#.
Why Overriding?
• Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
• Method overriding is used for runtime polymorphism.
• By combining inheritance with overridden methods, a superclass can define the
general form of the methods that will be used by all of its subclasses.
• Dynamic, run-time polymorphism is one of the most powerful mechanisms that
object-oriented design brings to bear on code reuse and robustness.
Method Overriding: Points to remember
• Method overriding occurs only when the names and the type signatures of the
two methods are identical. If they are not, then the two methods are simply
overloaded.
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Overloading vs Overriding
Overloading vs Overriding: Java Methods
Method Overloading Method Overriding
Overloading:Method with same name different signature Overriding:Method with same name same signature
Known as Compile-time Polymorphism Known as Run-time Polymorphism
It is performed within class. It occurs in two classes with IS-A (inheritance) relationship.
Inheritance and method hiding is not involved here. Here subclass method hides the super class method.

More Related Content

Similar to Inheritance_abstractclass_interface.pdf

Similar to Inheritance_abstractclass_interface.pdf (20)

Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
‫Chapter3 inheritance
‫Chapter3 inheritance‫Chapter3 inheritance
‫Chapter3 inheritance
 
Java
JavaJava
Java
 
Inheritance
Inheritance Inheritance
Inheritance
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 
Inheritance
InheritanceInheritance
Inheritance
 
6 Inheritance
6 Inheritance6 Inheritance
6 Inheritance
 
RajLec10.ppt
RajLec10.pptRajLec10.ppt
RajLec10.ppt
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading.NET F# Inheritance and operator overloading
.NET F# Inheritance and operator overloading
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
OOPS IN C++
OOPS IN C++OOPS IN C++
OOPS IN C++
 
Inheritance1
Inheritance1Inheritance1
Inheritance1
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
C++ presentation
C++ presentationC++ presentation
C++ presentation
 

Recently uploaded

Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxMd. Shahidul Islam Prodhan
 
fundamentals of drawing and isometric and orthographic projection
fundamentals of drawing and isometric and orthographic projectionfundamentals of drawing and isometric and orthographic projection
fundamentals of drawing and isometric and orthographic projectionjeevanprasad8
 
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and VisualizationKIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and VisualizationDr. Radhey Shyam
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdfKamal Acharya
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdfKamal Acharya
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdfKamal Acharya
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopEmre Günaydın
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdfKamal Acharya
 
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamKIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamDr. Radhey Shyam
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringC Sai Kiran
 
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringC Sai Kiran
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industriesMuhammadTufail242431
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234AafreenAbuthahir2
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfKamal Acharya
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf884710SadaqatAli
 
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-IVigneshvaranMech
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGKOUSTAV SARKAR
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdfKamal Acharya
 
Furniture showroom management system project.pdf
Furniture showroom management system project.pdfFurniture showroom management system project.pdf
Furniture showroom management system project.pdfKamal Acharya
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdfKamal Acharya
 

Recently uploaded (20)

Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptxCloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
Cloud-Computing_CSE311_Computer-Networking CSE GUB BD - Shahidul.pptx
 
fundamentals of drawing and isometric and orthographic projection
fundamentals of drawing and isometric and orthographic projectionfundamentals of drawing and isometric and orthographic projection
fundamentals of drawing and isometric and orthographic projection
 
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and VisualizationKIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
KIT-601 Lecture Notes-UNIT-5.pdf Frame Works and Visualization
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
Hall booking system project report .pdf
Hall booking system project report  .pdfHall booking system project report  .pdf
Hall booking system project report .pdf
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
İTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering WorkshopİTÜ CAD and Reverse Engineering Workshop
İTÜ CAD and Reverse Engineering Workshop
 
Automobile Management System Project Report.pdf
Automobile Management System Project Report.pdfAutomobile Management System Project Report.pdf
Automobile Management System Project Report.pdf
 
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data StreamKIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
KIT-601 Lecture Notes-UNIT-3.pdf Mining Data Stream
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-5 Notes for II-II Mechanical Engineering
 
Halogenation process of chemical process industries
Halogenation process of chemical process industriesHalogenation process of chemical process industries
Halogenation process of chemical process industries
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdf
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES  INTRODUCTION UNIT-IENERGY STORAGE DEVICES  INTRODUCTION UNIT-I
ENERGY STORAGE DEVICES INTRODUCTION UNIT-I
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
Furniture showroom management system project.pdf
Furniture showroom management system project.pdfFurniture showroom management system project.pdf
Furniture showroom management system project.pdf
 
Courier management system project report.pdf
Courier management system project report.pdfCourier management system project report.pdf
Courier management system project report.pdf
 

Inheritance_abstractclass_interface.pdf

  • 3. Inheritance • All of the classes have common attributes (Age, Height, Weight) and methods (Walk, Talk, Eat). • However, they have some special skills like Diagnose, Playfootball and Runbusiness. • In each of the classes, you would be copying the same code for Walk, Talk and Eat for each character. Attributes: Age, Height, Weight Methods: Talk() Walk() Eat() Diagnose() class Doctor Attributes: Age, Height, Weight Methods: Talk() Walk() Eat() Playfootball() class Footballer Attributes: Age, Height, Weight Methods: Talk() Walk() Eat() Runbusiness() class Businessman
  • 4. Inheritance • The mechanism of a class to derive properties and characteristics from another class is called Inheritance. • It is the most important feature of Object Oriented Programming. • Inheritance is the process, by which class can acquire(reuse) the properties and methods of another class. • Base Class: The class whose properties are inherited by sub class is called Base Class/Super class/Parent class. • Derived Class: The class that inherits properties from another class is called Sub class/Derived Class/Child class. • Inheritance is implemented using super class and sub class relationship in object-oriented languages. Base Class Derived Class
  • 5. Inheritance Methods: Diagnose() class Doctor Methods: Playfootball() class Footballer Methods: Runbusiness() class Businessman Attributes: Age, Height, Weight Methods: Talk() , Walk(), Eat() class Person class Person is called Base class These classes are called Derived class
  • 7. Inheritance: Advantages • Promotes reusability • When an existing code is reused, it leads to less development and maintenance costs. • It is used to generate more dominant objects. • Avoids duplicity and data redundancy. • Inheritance makes the sub classes follow a standard interface. Base Class Derived Class
  • 9. Introduction • Inheritance is the process, by which a class can acquire(reuse) the properties and methods of another class. • The mechanism of deriving a new class from an old class is called inheritance. • The new class is called derived class and old class is called base class. • The derived class may have all the features of the base class and the programmer can add new features to the derived class. • Inheritance is also known as “IS-A relationship” between parent and child classes. • For Example : • Car IS A Vehicle • Bike IS A Vehicle • EngineeringCollege IS A College • MedicalCollege IS A College • MCACollege IS A College
  • 10. Inheritance Example Attributes: privatevehicle class Car Attributes: publicvehicle class Bus Attributes: goodsvehicle class Truck Attributes: Engineno, color Methods: applybreaks() class Vehicle
  • 11. How to implement Inheritance in java • To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword. Syntax: class subclass-name extends superclass-name { // body of class… }
  • 12. Implementing Inheritance in java Class A Base Class Class B Derived Class class A { //SuperClass or ParentClass or BaseClass } class B extends A { //SubClass or ChildClass or DerivedClass } the keyword “extends” is used to create a subclass of A
  • 13. Implementing Inheritance in java 1. class Person 2. { 3. String name; 4. long contact; 5. } 6. class Employee extends Person 7. { 8. int empID; 9. String designation; 10.} 11.Class Customer extends Person 12.{ 13. int customerID; 14. int invoiceNo; 15.} Person name:String Contact:long Employee empID:int Designation:Strin g Customer customerID:int InvoiceNo:int
  • 14. Implementing Inheritance in java 1. class Person 2. { 3. String name; 4. long contact; 5. public void dispContact() 6. { System.out.println(“num=”+contact); 7. } 8. } 9. class Employee extends Person 10.{ 11. int empID; 12. String designation; 13.} 14.Class Customer extends Person 15.{ 16. int customerID; 17. int invoiceNo; 18.} Person name:String Contact:long dispContact():void Employee empID:int Designation:Strin g Customer customerID:int InvoiceNo:int
  • 16. Property of Inheritance Class A Base Class Class B Derived Class Derived Class B can access attributes and methods of Base class A Base class A can’t access attributes and methods of Derived Class B Derived Class B can’t access private members of Base class A A class member that has been declared as private will remain private to its class. It is not accessible by any code outside its class, including subclasses.
  • 19. Example1: InheritanceDemo.java 1. class A{ 2. protected int i; 3. int j; 4. void showij(){ 5. System.out.println("i="+i+" j="+j); 6. } 7. } 8. class B extends A{ //inheritance 9. int k; 10. void showk(){ 11. System.out.println("k="+k); 12. } 13. void add(){ System.out.println("i+j+k="+(i+j+k)); 14. } 15.} 16.class InheritanceDemo{ 17.public static void main(String[] args) 18. { 19. A superObjA= new A(); 20. superObjA.i=10; 21. superObjA.j=20; 22. B subObjB= new B(); 23. subObjB.k=30; 24. superObjA.showij(); 25. subObjB.showk(); 26. subObjB.add(); 27. } 28.} i=10 j=20 k=30 i+j+k=30 Outpu t
  • 20. Types of Inheritance in Java A B 1. Single Inheritance A B C 3. Multilevel Inheritance A C B 2. Hierarchical Inheritance A B C 4. Multiple Inheritance A C B D 5. Hybrid Inheritance Note: Multiple and Hybrid Inheritance is not supported in Java with the Class Inheritance, we can still use those Inheritance with Interface which we will learn in later part of the Unit
  • 22. Single Inheritance: InheritanceDemo.java 1. class A{ 2. protected int i; 3. int j; 4. void showij(){ 5. System.out.println("i="+i+" j="+j); 6. } 7. } 8. class B extends A{ //inheritance 9. int k; 10. void showk(){ 11. System.out.println("k="+k); 12. } 13. void add(){ System.out.println("i+j+k="+(i+j+k)); 14. } 15.} 16.class InheritanceDemo{ 17.public static void main(String[] args) 18. { 19. A superObjA= new A(); 20. superObjA.i=10; 21. superObjA.j=20; 22. B subObjB= new B(); 23. subObjB.i=100 24. subObjB.j=100; 25. subObjB.k=30; 26. superObjA.showij(); 27. subObjB.showk(); 28. subObjB.add(); 29. } 30.} i=10 j=20 k=30 i+j+k=230 Outpu t A B
  • 24. OOP Java is the easiest, scoring and my favorite subject 1. class A{ 2. protected int i; 3. int j; 4. void showij(){ 5. System.out.println("inside class A:i="+i+" j="+j); 6. } 7. } 8. class B extends A{ 9. int k; 10. void showk(){ System.out.println("inside class B:k="+k); 11. } 12. void add_ijk(){ System.out.println(i+"+"+j+"+"+ k+"="+(i+j+k)); 13. }} 14.class C extends A{ 15. int m; 16. void showm(){ 17. System.out.println("inside class C:k="+m); 18. } 19. void add_ijm(){ 20. System.out.println(i+"+"+j+ "+"+m+"="+(i+j+m)); 21. } 22.} InheritanceLevel.java A C B
  • 25. OOP Java is the easiest, scoring and my favorite subject 23.class InheritanceLevel{ 24. public static void main(String[] args) { 25. A superObjA= new A(); 26. superObjA.i=10; 27. superObjA.j=20; 28. superObjA.showij(); 29. B subObjB= new B(); 30. subObjB.i=100; 31. subObjB.j=200; 32. subObjB.k=300; 33. subObjB.showk(); 34. subObjB.add_ijk(); 35. C subObjC= new C(); 36. subObjC.i=1000; 37. subObjC.j=2000;; 38. subObjC.m=3000; 39. subObjC.showm(); 40. subObjC.add_ijm(); 41. } 42.} inside class A:i=10 j=20 inside class B:k=300 100+200+300=600 inside class C:k=3000 1000+2000+3000=6000 Outpu t A C B InheritanceLevel.java
  • 27. OOP Java is the easiest, scoring and my favorite subject 1. class A{ 2. protected int i; 3. int j; 4. void showij(){ 5. System.out.println("inside class A:i="+i+" j="+j); 6. } 7. } 8. class B extends A{ 9. int k; 10. void showk(){ System.out.println("inside class B:k="+k); 11. } 12. void add_ijk(){ System.out.println(i+"+"+j+"+"+ k+"="+(i+j+k)); 13. }} 14.class C extends B{ 15. int m; 16. void showm(){ 17. System.out.println("inside class C:k="+m); 18. } 19. void add_ijkm(){ 20. System.out.println(i+"+"+j+ "+"+k+"+"+m+"="+(i+j+k+m)); 21. } 22.} InheritanceMultilevel.java A B C
  • 28. OOP Java is the easiest, scoring and my favorite subject 23.class InheritanceMultilevel{ 24. public static void main(String[] args) { 25. A superObjA= new A(); 26. superObjA.i=10; 27. superObjA.j=20; 28. superObjA.showij(); 29. B subObjB= new B(); 30. subObjB.i=100; 31. subObjB.j=200; 32. subObjB.k=300; 33. subObjB.showk(); 34. subObjB.add_ijk(); 35. C subObjC= new C(); 36. subObjC.i=1000; 37. subObjC.j=2000; 38. subObjC.k=3000; 39. subObjC.m=4000; 40. subObjC.showm(); 41. subObjC.add_ijkm(); 42. } inside class A:i=10 j=20 inside class B:k=300 100+200+300=600 inside class C:k=4000 1000+2000+3000+4000=10000 Outpu t A B C InheritanceMultilevel.java
  • 29. Derived Class with Constructor
  • 30. Derived Class with Constructor Cube # height: double # width: double # depth: double Cube() volume(): double CubeWeight # weigth: double CubeWeight(double, double, double, double):double CubeInherit cw1:CubeWeight cw2:CubeWeight main(): void
  • 31. OOP Java is the easiest, scoring and my favorite subject 1. class Cube{ 2. protected double height,width,depth; 3. Cube(){ 4. System.out.println("inside 5. default Constructor:CUBE"); 6. } 7. double volume(){ 8. return height*width*depth; 9. } 10.} 11.class CubeWeight extends Cube{ 12.double weigth; 13.CubeWeight(double h,double w,double d, double m) 14.{ 15. System.out.println("inside Constructor: 16. CUBEWEIGTH"); 17. height=h; 18. width=w; 19. depth=d; 20. weigth=m; 21. }} 22.class CubeInherit{ 23. public static void main(String[] args) { 24.CubeWeight cw1= new 25. CubeWeight(10,10,10,20.5); 26.CubeWeight cw2= new 27. CubeWeight(100,100,100,200.5); 28.System.out.println("cw1.volume()=" +cw1.volume()); 29.System.out.println("cw2.volume()=" +cw2.volume()); 30. }} CubeInherit.java inside default Constructor:CUBE inside Constructor:CUBEWEIGTH inside default Constructor:CUBE inside Constructor:CUBEWEIGTH cw1.volume()=1000.0 cw2.volume()=1000000.0 Outpu t
  • 33. Super Keyword • Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. Super has two general forms: 1. Calls the superclass constructor. 2. Used to access a members(i.e. instance variable or method) of the superclass.
  • 34. Using super to Call Superclass Constructors • Call to super must be first statement in constructor Cube # height: double # width: double # depth: double volume(): double CubeWeight # weigth: double CubeInherit cw1:CubeWeight cw2:CubeWeight main(): void Using “super” Cube(double, double, double) CubeWeight(double, double, double, double)
  • 35. OOP Java is the easiest, scoring and my favorite subject 1. class Cube{ 2. protected double height,width,depth; 3. Cube(double h,double w,double d){ 4. System.out.println("Constructor: 5. CUBE"); 6. height=h; 7. width=w; 8. depth=d; 9. } 10. double volume(){ 11. return height*width*depth; 12. } 13.} 14.class CubeWeight extends Cube{ 15. double weigth; 16. CubeWeight(double h,double w,double d, double m){ 17. super(h,w,d); //call superclassConstructor 18. System.out.println("Constructor:CUBEWEIGTH"); 19. weigth=m; 20. } 21.} 22. class CubeInheritSuper{ 23. public static void main(String[] args) { 24. CubeWeight cw1= new CubeWeight(10,10,10,20.5); 25. CubeWeight cw2= new CubeWeight(100,100,100,200.5); 26. System.out.println("cw1.volume()="+cw1.volume()); 27. System.out.println("cw1.weigth="+cw1.weigth); 28. System.out.println("cw2.volume()="+cw2.volume()); 29. System.out.println("cw2.weigth="+cw2.weigth); 30. } 31. } CubeInheritSuper.java Constructor:CUBE Constructor:CUBEWEIGTH Constructor:CUBE Constructor:CUBEWEIGTH cw1.volume()=1000.0 cw1.weigth=20.5 cw2.volume()=1000000.0 cw2.weigth=200.5 Outpu t Using super to Call Superclass Constructors
  • 36. Using super to access members • The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. • Syntax: • This second form of super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. super.member member can be either a method or an instance variable.
  • 37. Using super to access members: SuperMemberDemo.java 1. class A{ 2. 3. } 4. class B extends A{ 5. int i,k; 6. B(int a,int b){ 7. 8. this.i=b; 9. } 10. void show(){ 11. System.out.println("super.i="+super.i); 12. System.out.println("this.i="+this.i); 13. } 14.} 15.class SuperMemberDemo{ 16. public static void main(String[] args) 17. { 18. B b= new B(12,56); 19. b.show(); 20. } 21.} super.i=12 this.i=56 Outpu t super.i=a; int i;
  • 38. Using super to access members: SuperMemberDemo.java 1. class A{ 2. int i=33; 3. void show(){ 4. System.out.println("inside A:i="+i); 5. } 6. } 7. class B extends A{ 8. int i,k; 9. B(int a,int b){ 10. super.show(); 11. super.i=a; 12. this.i=b; 13. } 14. void show(){ 15. System.out.println("super.i="+super.i); 16. System.out.println("this.i="+this.i); 17. } 18.} 19.class SuperMemberDemo{ 20. public static void main(String[] args) 21. { 22. B b= new B(12,56); 23. b.show(); 24. } 25.} inside A:i=33 super.i=12 B.i=56 Outpu t
  • 39. Points to remember for super • When a subclass calls super( ), it is calling the constructor of its immediate superclass. • This is true even in a multileveled hierarchy. • super( ) must always be the first statement executed inside a subclass constructor. • If a constructor does not explicitly call a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. • The most common application of super keyword is to eliminate the ambiguity between members of superclass and sub class.
  • 40. Why Inheritance 1. Reusability of code 2. To implement polymorphism at run time (method overriding). Class A Base Class Class B Derived Class
  • 42. Access Control Access Modifier Description Private(-) The access level of a private modifier is only within the class. It cannot be accessed from outside the class. 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. 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. 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.
  • 43. Access Control Access Modifier Same Class Same Package Sub Class Universal Private Default Protected Public
  • 44. Exercise 1. Why multiple and Hybrid inheritance is not supported in java. 2. Implement inheritance in java using following diagram. Shape #String name + String color Shape() Circle ~ radius: double ~PI: double calCircleArea(): double Rectangle ~height: double ~width: double calRectArea(): double Triangle ~length: double ~width: double calTriArea(): double
  • 45. Interview Questions 1. Which class in Java is superclass of every other class? 2. Can a class extend itself? 3. Can we assign superclass to subclass? 4. Can a class extend more than one class?
  • 47. Polymorphism Polymorphism: It is a Greek term means, “One name many Forms” Polymorphism Poly: Many Morphism: Types  Most important concept of object oriented programming  In OOP, Polymorphism is the ability of an object to take on many forms.
  • 48. Polymorphism • Polymorphism is the method in an object-oriented programming language that does different things depending on the class of the object which calls it. • Polymorphism can be implemented using the concept of overloading and overriding.
  • 49. Polymorphism: Advantages • Single variable can be used to store multiple data types. • Easy to debug the codes. • It allows to perform a single act in different ways. • Polymorphism allows the object to decide which form of the function to implement at compile-time (overloading) as well as run- time (overriding). • Reduces coupling, increases reusability and makes code easier to read.
  • 54. Method Overloading: Compile-time Polymorphism • Definition: When two or more methods are implemented that share same name but different parameter(s), the methods are said to be overloaded, and the process is referred to as method overloading • Method overloading is one of the ways that Java implements polymorphism. • 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. • E.g. public void draw() public void draw(int height, int width) public void draw(int radius) • Thus, overloaded methods must differ in the type and/or number of their parameters. • While in overloaded methods with different return types and same name & parameter are not allowed ,as the return type alone is insufficient for the compiler to distinguish two versions of a method.
  • 55. Method Overloading: Compile-time Polymorphism 1. class Addition{ 2. int i,j,k; 3. void add(int a){ 4. i=a; 5. System.out.println("add i="+i); 6. } 7. void add(int a,int b){overloaded add() 8. i=a; 9. j=b; 10. System.out.println("add i+j="+(i+j)); 11. } 12. void add(int a,int b,int c){overloaded add() 13. i=a; 14. j=b; 15. k=c; 16. System.out.println("add i+j+k="+(i+j+k)); 17. } 18.} 19.class OverloadDemo{ 20.public static void main(String[] args){ 21. Addition a1= new Addition(); 22. //call all versions of add() 23. a1.add(20); 24. a1.add(30,50); 25. a1.add(10,30,60); 26. } 27.} add i=20 add i+j=80 add i+j+k=100 Outpu t
  • 57. Method Overriding: Run-time Polymorphism • In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. • Definition: If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in Java.
  • 58. Method Overriding: OverrideDemo.java 1. class Shape{ 2. void draw(){ 3. System.out.println("Draw Shape"); 4. } 5. } 6. class Circle extends Shape{ 7. void draw(){ 8. System.out.println("Draw Circle"); 9. } 10.} 11.class Square extends Shape{ 12. void draw(){ 13. System.out.println("Draw Square"); 14. } 15.} 1. class OverrideDemo{ 2. public static void main(String[] args) { 3. Circle c= new Circle(); 4. c.draw(); //child class meth() 5. Square sq= new Square(); 6. sq.draw();//child class meth() 7. Shape sh= new Shape(); 8. sh.draw();//parentClass meth() 9. } 10.} Draw Circle Draw Square Draw Shape Outpu t When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
  • 59. Method Overriding: OverrideDemo.java 1. class Shape{ 2. void draw(){ 3. System.out.println("Draw Shape"); 4. } 5. } 6. class Circle extends Shape{ 7. void draw(){ 8. 9. System.out.println("Draw Circle"); 10. } 11.} 12.class Square extends Shape{ 13. void draw(){ 14. System.out.println("Draw Square"); 15. } 16.} 1. class OverrideDemo{ 2. public static void main(String[] args) { 3. Circle c= new Circle(); 4. c.draw(); 5. Square sq= new Square(); 6. sq.draw(); 7. } 8. } Draw Shape Draw Circle Draw Square Outpu t super.draw(); Here, super.draw( ) calls the superclass version of draw( ). Overridden methods in Java are similar to virtual functions in C++ and C#.
  • 60. Why Overriding? • Method overriding is used to provide the specific implementation of a method which is already provided by its superclass. • Method overriding is used for runtime polymorphism. • By combining inheritance with overridden methods, a superclass can define the general form of the methods that will be used by all of its subclasses. • Dynamic, run-time polymorphism is one of the most powerful mechanisms that object-oriented design brings to bear on code reuse and robustness.
  • 61. Method Overriding: Points to remember • Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. • The method must have the same name as in the parent class • The method must have the same parameter as in the parent class. • There must be an IS-A relationship (inheritance).
  • 63. Overloading vs Overriding: Java Methods Method Overloading Method Overriding Overloading:Method with same name different signature Overriding:Method with same name same signature Known as Compile-time Polymorphism Known as Run-time Polymorphism It is performed within class. It occurs in two classes with IS-A (inheritance) relationship. Inheritance and method hiding is not involved here. Here subclass method hides the super class method.