SlideShare a Scribd company logo
1 of 44
Lecturer :Ashna nazm hamasalh
ashnanazm2@gmail.com
Kirkuk institute for computer science
lecturer .miss .Ashna Nazm Hamasalh 1
Chapter One
Introduction to OOP
in JAVA
lecturer .miss .Ashna Nazm Hamasalh 2
Introduction
This tutorial will help you to understand about Java OOP’S concepts with
examples. Let’s discuss about what are the features of (Object Oriented
Programming). Writing object-oriented programs involves creating classes,
creating objects from those classes, and creating applications, which are
stand-alone executable programs that use those objects.
lecturer .miss .Ashna Nazm Hamasalh 3
A class is a template, blue print, or contract that defines what an
object’s data fields and methods will be.
An object is an instance of a class. You can create many instances of a
class.
A Java class uses variables to define data fields and methods to define
actions. Additionally, a class provides methods of a special type, known
as constructors, which are invoked to create a new object. A
constructor can perform any action, but constructors are designed to
perform initializing actions, such as initializing the data fields of objects.
lecturer .miss .Ashna Nazm Hamasalh 4
lecturer .miss .Ashna Nazm Hamasalh 5
Objects are made up of attributes and methods. Attributes are the
characteristics that define an object; the values contained in attributes
differentiate objects of the same class from one another. To understand
this better let’s take example of Mobile as object. Mobile has
characteristics like model, manufacturer, cost, operating system etc. So
if we create “Samsung” mobile object and “IPhone” mobile object we
can distinguish them from characteristics. The values of the attributes
of an object are also referred to as the object’s state.
lecturer .miss .Ashna Nazm Hamasalh 6
There are three main features of OOPS.
1) Inheritance
2)Polymorphism
3) Encapsulation
lecturer .miss .Ashna Nazm Hamasalh 7
lecturer .miss .Ashna Nazm Hamasalh 8
Chapter Two
Inheritance, Polymorphism,
Abstract, Interface and
Package
lecturer .miss .Ashna Nazm Hamasalh 9
Inheritance
Inheritance can be defined as the process where one class acquires the
properties(methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass
(derived class, child class) and the class whose properties are inherited is
known as superclass(base class, parent class).
lecturer .miss .Ashna Nazm Hamasalh 10
lecturer .miss .Ashna Nazm Hamasalh 11
extends Keyword
extends is the keyword used to inherit the properties of a class. Below
given is the syntax of extends keyword.
lecturer .miss .Ashna Nazm Hamasalh 12
class Super{
.....
.....
}
class Sub extends Super{
.....
.....
}
lecturer .miss .Ashna Nazm Hamasalh 13
Sample Code
Below given is an example demonstrating Java inheritance. In this
example you
can observe two classes namely Calculation and My_Calculation.
Using extends keyword the My_Calculation inherits the methods
addition() and
Subtraction() of Calculation class.
Copy and paste the program given below in a file with name
My_Calculation.java
lecturer .miss .Ashna Nazm Hamasalh 14
public class My_Calculation extends Calculation{
public void multiplication(int x, int y){
z=x*y;
System.out.println("The product of the given numb
ers:"+z);
}
public static void main(String args[]){
int a=20, b=10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Substraction(a, b);
demo.multiplication(a, b); } }
class Calculation{
int z;
public void addition(int x, int y){
z=x+y;
System.out.println("The sum of the given numbers:"+z);
}
public void Substraction(int x,int y){
z=x-y;
System.out.println("The difference between the given n
umbers:"+z);
}
}
Child class parent class
lecturer .miss .Ashna Nazm Hamasalh 15
After executing the program it will produce the foll
owing result.
•The sum of the given numbers:30
•The difference between the given numbers:10
•The product of the given numbers:200
lecturer .miss .Ashna Nazm Hamasalh 16
In the given program when an object to My_Calculation class is created,
a copy of the contents of the super class is made with in it.
That is why, using the object of the subclass you can access the members
of a super class.
lecturer .miss .Ashna Nazm Hamasalh 17
The Superclass reference variable can hold the subclass object, but using that
variable you can access only the members of the superclass, so to access the
members of both classes it is recommended to always create reference variable
to the subclass.
If you consider the above program you can instantiate the class as given below as
well. But using the superclass reference variable ( cal in this case ) you cannot call
the method multiplication(), which belongs to the subclass My_Calculation.
Calculation cal=new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
lecturer .miss .Ashna Nazm Hamasalh 18
lecturer .miss .Ashna Nazm Hamasalh 19
Note: A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members, so they are not inherited by
subclasses, but the constructor of the superclass can be invoked from the subclass.
The super keyword
The super keyword is similar to this keyword following are the scenarios
where the super keyword is used.
• It is used to differentiate the members of superclass from the members
of subclass, if they have same names.
• It is used to invoke the superclass constructor from subclass.
lecturer .miss .Ashna Nazm Hamasalh 20
Differentiating the members
If a class is inheriting the properties of another class. And if the members of the
superclass have the names same as the sub class, to differentiate these variables
we use super keyword as shown below.
super.variable
super.method();
lecturer .miss .Ashna Nazm Hamasalh 21
Sample Code
This section provides you a program that demonstrates the usage of
the super keyword.
In the given program you have two classes namely Sub_class and Super_class, both
have a method named display() with different implementations, and a variable
named num with different values. We are invoking display() method of both
classes and printing the value of the variable num of both classes, here you can
observe that we have used super key word to differentiate the members of super
class from sub class.
Copy and paste the program in a file with name Sub_class.java.
lecturer .miss .Ashna Nazm Hamasalh 22
lecturer .miss .Ashna Nazm Hamasalh 23
class Super_class{
int num=20;
//display method of superclass
public void display(){
System.out.println("This is the display method of superclass");
}
}
public class Sub_class extends Super_class {
int num=10;
//display method of sub class
public void display(){
System.out.println("This is the display method
of subclass");
}
public void my_method(){
//Instantiating subclass
Sub_class sub=new Sub_class();
//Invoking the display() method of sub class
sub.display();
//Invoking the display() method of superclass
super.display();
//printing the value of variable num of subclass
System.out.println("value of the variable
named num in sub class:"+ sub.num);
//printing the value of variable num of superclass
System.out.println("value of the variable
named num in super class:"+super.num);
}
public static void main(String args[]){
Sub_class obj = new Sub_class();
obj.my_method();
}
}
lecturer .miss .Ashna Nazm Hamasalh 24
Compile and execute the above code .
On executing the program you will get the following result:
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
•
lecturer .miss .Ashna Nazm Hamasalh 25
Invoking Superclass constructor
If a class is inheriting the properties of another class, the subclass automatically
acquires the default constructor of the super class. But if you want to call a
parameterized constructor of the super class, you need to use the super keyword
as shown below.
lecturer .miss .Ashna Nazm Hamasalh 26
super(values);
Sample Code
The program given in this section demonstrates how to use the super keyword to
invoke the parameterized constructor of the superclass. This program contains a
super class and a sub class, where the super class contains a parameterized
constructor which accepts a string value, and we used the super keyword to
invoke the parameterized constructor of the super class.
Copy and paste the below given program in a file with name Subclass.java
lecturer .miss .Ashna Nazm Hamasalh 27
Compile and execute the above code
On executing the program you will get the following result:
The value of the variable named age in super class is: 24
class Superclass{
int age;
Superclass(int age){
this.age=age;
}
public void getAge(){
System.out.println("The value of the
variable named age in super class is: "+age);
}
}
public class Subclass extends Superclass {
Subclass(int age){
super(age);
}
public static void main(String argd[]){
Subclass s= new Subclass(24);
s.getAge();
}
}
lecturer .miss .Ashna Nazm Hamasalh 28
Types of inheritance
There are various types of inheritance as demonstrated below.
lecturer .miss .Ashna Nazm Hamasalh 29
What is polymorphism in programming?
Polymorphism is the capability of a method to do different things based
on the object that it is acting upon. In other words, polymorphism
allows you define one interface and have multiple implementations.
I know it sounds confusing. Don’t worry we will discuss this in detail.
lecturer .miss .Ashna Nazm Hamasalh 30
• It is a feature that allows one interface to be used for a general class
of actions.
• An operation may exhibit different behavior in different instances.
• The behavior depends on the types of data used in the operation.
• It plays an important role in allowing objects having different internal
structures to share the same external interface.
• Polymorphism is extensively used in implementing inheritance.
Following concepts demonstrate different types of polymorphism in java.
1) Method Overloading
2) Method Overriding
lecturer .miss .Ashna Nazm Hamasalh 31
Method Overloading:
In Java, it is possible to define two or more methods of same name in a
class,provided that there argument list or parameters are different. This
concept is known as Method Overloading.
I have covered method overloading and Overriding below. To know
more about
polymorphism types refer my post Types of polymorphism in java: Stat
ic,
Dynamic, Runtime and Compile time Polymorphism.
lecturer .miss .Ashna Nazm Hamasalh 32
1) Method Overloading
1. To call an overloaded method in Java, it is must to use the type and/or
number of arguments to determine which version of the overloaded method to
actually call.
2. Overloaded methods may have different return types; the return type alone
is insufficient to distinguish two versions of a method.
3. 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.
4. It allows the user to achieve compile time polymorphism.
5. An overloaded method can throw different exceptions.
6. It can have different access modifiers.
lecturer .miss .Ashna Nazm Hamasalh 33
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
}}
Example:
class Overload
{void demo (int a){
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}}
lecturer .miss .Ashna Nazm Hamasalh 34
Output:
a: 10
a and b: 10,20
Here the method demo() is overloaded 3 times: first having 1 int paramete
r,second one has 2 int parameters and third one is having double arg. The
methodsare invoked or called with the same type and number of paramete
rs used.
lecturer .miss .Ashna Nazm Hamasalh 35
Rules for Method Overloading
1. Overloading can take place in the same class or in its sub-class.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. Overloaded method should always be the part of the same class (can also take
place in sub class), with same name but different parameters.
5. The parameters may differ in their type or number, or in both.
6. They may have the same or different return types.
7. It is also known as compile time polymorphism.
lecturer .miss .Ashna Nazm Hamasalh 36
2) Method Overriding
Child class has the same method as of base class. In such cases child class
overrides the parent class method without even touching the source code
of the base class. This feature is known as method overriding.
lecturer .miss .Ashna Nazm Hamasalh 37
Example:
public class BaseClass
{
public void methodToOverride() //Base class method
{System.out.println ("I'm the method of BaseClass");
}}
lecturer .miss .Ashna Nazm Hamasalh 38
public class DerivedClass extends BaseClass
{
public void methodToOverride() //Derived Class method
{
System.out.println ("I'm the method of DerivedClass");
}
}
Output:
I'm the method of BaseClass
I'm the method of DerivedClass
public class TestMethod{
public static void main (String args []) {
// BaseClass reference and object
BaseClass obj1 = new BaseClass();
// BaseClass reference but DerivedClass object
BaseClass obj2 = new DerivedClass();
// Calls the method from BaseClass class
obj1.methodToOverride();
//Calls the method from DerivedClass class
obj2.methodToOverride();}}
lecturer .miss .Ashna Nazm Hamasalh 39
Rules for Method Overriding:
1. applies only to inherited methods
2. object type (NOT reference variable type) determines which overridden
method will be used at runtime
3. Overriding method can have different return type (refer this)
4. Overriding method must not have more restrictive access modifier
5. Abstract methods must be overridden
6. Static and final methods cannot be overridden
7. Constructors cannot be overridden
8. It is also known as Runtime polymorphism.
lecturer .miss .Ashna Nazm Hamasalh 40
super keyword in Overriding:
When invoking a superclass version of an overridden method the super keyword
is used.
lecturer .miss .Ashna Nazm Hamasalh 41
Example:
lecturer .miss .Ashna Nazm Hamasalh 42
class Vehicle {
public void move () {
System.out.println ("Vehicles are used for moving from one place to another");}}
class Car extends Vehicle {
public void move () {
super. move (); // invokes the super class method
System.out.println ("Car is a good medium of transport ");}}
public class TestCar {
public static void main (String args []){
Vehicle b = new Car (); // Vehicle reference but Car object
b.move (); //Calls the method in Car class
}}
Output:
Vehicles are used for moving from one place to another
Car is a good medium of transport
lecturer .miss .Ashna Nazm Hamasalh 43
44
lecturer .miss .Ashna Nazm Hamasalh

More Related Content

What's hot

Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract ClassOUM SAOKOSAL
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism JavaM. Raihan
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keywordtanu_jaswal
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismEduardo Bergavera
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingShivam Singhal
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritanceteach4uin
 
Seminar on java
Seminar on javaSeminar on java
Seminar on javashathika
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Nuzhat Memon
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in javaAtul Sehdev
 
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية Mahmoud Alfarra
 

What's hot (20)

Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
 
Inheritance and Polymorphism Java
Inheritance and Polymorphism JavaInheritance and Polymorphism Java
Inheritance and Polymorphism Java
 
Inheritance
InheritanceInheritance
Inheritance
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
Chapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and PolymorphismChapter 13 - Inheritance and Polymorphism
Chapter 13 - Inheritance and Polymorphism
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Abstract classes and interfaces
Abstract classes and interfacesAbstract classes and interfaces
Abstract classes and interfaces
 
L7 inheritance
L7 inheritanceL7 inheritance
L7 inheritance
 
Seminar on java
Seminar on javaSeminar on java
Seminar on java
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Abstract class
Abstract classAbstract class
Abstract class
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)Std 12 computer chapter 8 classes and object in java (part 2)
Std 12 computer chapter 8 classes and object in java (part 2)
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
itft-Inheritance in java
itft-Inheritance in javaitft-Inheritance in java
itft-Inheritance in java
 
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
 
Polymorphism in java
Polymorphism in javaPolymorphism in java
Polymorphism in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Oop
OopOop
Oop
 

Similar to Inheritance and Polymorphism in java simple and clear

Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance SlidesAhsan Raja
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppthenokmetaferia1
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceKuntal Bhowmick
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in javachauhankapil
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsMaryo Manjaruni
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshowilias ahmed
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: InheritanceTareq Hasan
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritanceraksharao
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxnaeemcse
 

Similar to Inheritance and Polymorphism in java simple and clear (20)

java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Presentation 3.pdf
Presentation 3.pdfPresentation 3.pdf
Presentation 3.pdf
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
Only oop
Only oopOnly oop
Only oop
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Chap-3 Inheritance.pptx
Chap-3 Inheritance.pptxChap-3 Inheritance.pptx
Chap-3 Inheritance.pptx
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
PROGRAMMING IN JAVA
PROGRAMMING IN JAVAPROGRAMMING IN JAVA
PROGRAMMING IN JAVA
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Chap3 inheritance
Chap3 inheritanceChap3 inheritance
Chap3 inheritance
 
Sdtl assignment 03
Sdtl assignment 03Sdtl assignment 03
Sdtl assignment 03
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Core java oop
Core java oopCore java oop
Core java oop
 
Ppt of c++ vs c#
Ppt of c++ vs c#Ppt of c++ vs c#
Ppt of c++ vs c#
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
 

Recently uploaded

Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 

Recently uploaded (20)

Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 

Inheritance and Polymorphism in java simple and clear

  • 1. Lecturer :Ashna nazm hamasalh ashnanazm2@gmail.com Kirkuk institute for computer science lecturer .miss .Ashna Nazm Hamasalh 1
  • 2. Chapter One Introduction to OOP in JAVA lecturer .miss .Ashna Nazm Hamasalh 2
  • 3. Introduction This tutorial will help you to understand about Java OOP’S concepts with examples. Let’s discuss about what are the features of (Object Oriented Programming). Writing object-oriented programs involves creating classes, creating objects from those classes, and creating applications, which are stand-alone executable programs that use those objects. lecturer .miss .Ashna Nazm Hamasalh 3
  • 4. A class is a template, blue print, or contract that defines what an object’s data fields and methods will be. An object is an instance of a class. You can create many instances of a class. A Java class uses variables to define data fields and methods to define actions. Additionally, a class provides methods of a special type, known as constructors, which are invoked to create a new object. A constructor can perform any action, but constructors are designed to perform initializing actions, such as initializing the data fields of objects. lecturer .miss .Ashna Nazm Hamasalh 4
  • 5. lecturer .miss .Ashna Nazm Hamasalh 5
  • 6. Objects are made up of attributes and methods. Attributes are the characteristics that define an object; the values contained in attributes differentiate objects of the same class from one another. To understand this better let’s take example of Mobile as object. Mobile has characteristics like model, manufacturer, cost, operating system etc. So if we create “Samsung” mobile object and “IPhone” mobile object we can distinguish them from characteristics. The values of the attributes of an object are also referred to as the object’s state. lecturer .miss .Ashna Nazm Hamasalh 6
  • 7. There are three main features of OOPS. 1) Inheritance 2)Polymorphism 3) Encapsulation lecturer .miss .Ashna Nazm Hamasalh 7
  • 8. lecturer .miss .Ashna Nazm Hamasalh 8
  • 9. Chapter Two Inheritance, Polymorphism, Abstract, Interface and Package lecturer .miss .Ashna Nazm Hamasalh 9
  • 10. Inheritance Inheritance can be defined as the process where one class acquires the properties(methods and fields) of another. With the use of inheritance the information is made manageable in a hierarchical order. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass(base class, parent class). lecturer .miss .Ashna Nazm Hamasalh 10
  • 11. lecturer .miss .Ashna Nazm Hamasalh 11
  • 12. extends Keyword extends is the keyword used to inherit the properties of a class. Below given is the syntax of extends keyword. lecturer .miss .Ashna Nazm Hamasalh 12 class Super{ ..... ..... } class Sub extends Super{ ..... ..... }
  • 13. lecturer .miss .Ashna Nazm Hamasalh 13
  • 14. Sample Code Below given is an example demonstrating Java inheritance. In this example you can observe two classes namely Calculation and My_Calculation. Using extends keyword the My_Calculation inherits the methods addition() and Subtraction() of Calculation class. Copy and paste the program given below in a file with name My_Calculation.java lecturer .miss .Ashna Nazm Hamasalh 14
  • 15. public class My_Calculation extends Calculation{ public void multiplication(int x, int y){ z=x*y; System.out.println("The product of the given numb ers:"+z); } public static void main(String args[]){ int a=20, b=10; My_Calculation demo = new My_Calculation(); demo.addition(a, b); demo.Substraction(a, b); demo.multiplication(a, b); } } class Calculation{ int z; public void addition(int x, int y){ z=x+y; System.out.println("The sum of the given numbers:"+z); } public void Substraction(int x,int y){ z=x-y; System.out.println("The difference between the given n umbers:"+z); } } Child class parent class lecturer .miss .Ashna Nazm Hamasalh 15
  • 16. After executing the program it will produce the foll owing result. •The sum of the given numbers:30 •The difference between the given numbers:10 •The product of the given numbers:200 lecturer .miss .Ashna Nazm Hamasalh 16
  • 17. In the given program when an object to My_Calculation class is created, a copy of the contents of the super class is made with in it. That is why, using the object of the subclass you can access the members of a super class. lecturer .miss .Ashna Nazm Hamasalh 17
  • 18. The Superclass reference variable can hold the subclass object, but using that variable you can access only the members of the superclass, so to access the members of both classes it is recommended to always create reference variable to the subclass. If you consider the above program you can instantiate the class as given below as well. But using the superclass reference variable ( cal in this case ) you cannot call the method multiplication(), which belongs to the subclass My_Calculation. Calculation cal=new My_Calculation(); demo.addition(a, b); demo.Subtraction(a, b); lecturer .miss .Ashna Nazm Hamasalh 18
  • 19. lecturer .miss .Ashna Nazm Hamasalh 19 Note: A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.
  • 20. The super keyword The super keyword is similar to this keyword following are the scenarios where the super keyword is used. • It is used to differentiate the members of superclass from the members of subclass, if they have same names. • It is used to invoke the superclass constructor from subclass. lecturer .miss .Ashna Nazm Hamasalh 20
  • 21. Differentiating the members If a class is inheriting the properties of another class. And if the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below. super.variable super.method(); lecturer .miss .Ashna Nazm Hamasalh 21
  • 22. Sample Code This section provides you a program that demonstrates the usage of the super keyword. In the given program you have two classes namely Sub_class and Super_class, both have a method named display() with different implementations, and a variable named num with different values. We are invoking display() method of both classes and printing the value of the variable num of both classes, here you can observe that we have used super key word to differentiate the members of super class from sub class. Copy and paste the program in a file with name Sub_class.java. lecturer .miss .Ashna Nazm Hamasalh 22
  • 23. lecturer .miss .Ashna Nazm Hamasalh 23 class Super_class{ int num=20; //display method of superclass public void display(){ System.out.println("This is the display method of superclass"); } }
  • 24. public class Sub_class extends Super_class { int num=10; //display method of sub class public void display(){ System.out.println("This is the display method of subclass"); } public void my_method(){ //Instantiating subclass Sub_class sub=new Sub_class(); //Invoking the display() method of sub class sub.display(); //Invoking the display() method of superclass super.display(); //printing the value of variable num of subclass System.out.println("value of the variable named num in sub class:"+ sub.num); //printing the value of variable num of superclass System.out.println("value of the variable named num in super class:"+super.num); } public static void main(String args[]){ Sub_class obj = new Sub_class(); obj.my_method(); } } lecturer .miss .Ashna Nazm Hamasalh 24
  • 25. Compile and execute the above code . On executing the program you will get the following result: This is the display method of subclass This is the display method of superclass value of the variable named num in sub class:10 value of the variable named num in super class:20 • lecturer .miss .Ashna Nazm Hamasalh 25
  • 26. Invoking Superclass constructor If a class is inheriting the properties of another class, the subclass automatically acquires the default constructor of the super class. But if you want to call a parameterized constructor of the super class, you need to use the super keyword as shown below. lecturer .miss .Ashna Nazm Hamasalh 26
  • 27. super(values); Sample Code The program given in this section demonstrates how to use the super keyword to invoke the parameterized constructor of the superclass. This program contains a super class and a sub class, where the super class contains a parameterized constructor which accepts a string value, and we used the super keyword to invoke the parameterized constructor of the super class. Copy and paste the below given program in a file with name Subclass.java lecturer .miss .Ashna Nazm Hamasalh 27
  • 28. Compile and execute the above code On executing the program you will get the following result: The value of the variable named age in super class is: 24 class Superclass{ int age; Superclass(int age){ this.age=age; } public void getAge(){ System.out.println("The value of the variable named age in super class is: "+age); } } public class Subclass extends Superclass { Subclass(int age){ super(age); } public static void main(String argd[]){ Subclass s= new Subclass(24); s.getAge(); } } lecturer .miss .Ashna Nazm Hamasalh 28
  • 29. Types of inheritance There are various types of inheritance as demonstrated below. lecturer .miss .Ashna Nazm Hamasalh 29
  • 30. What is polymorphism in programming? Polymorphism is the capability of a method to do different things based on the object that it is acting upon. In other words, polymorphism allows you define one interface and have multiple implementations. I know it sounds confusing. Don’t worry we will discuss this in detail. lecturer .miss .Ashna Nazm Hamasalh 30
  • 31. • It is a feature that allows one interface to be used for a general class of actions. • An operation may exhibit different behavior in different instances. • The behavior depends on the types of data used in the operation. • It plays an important role in allowing objects having different internal structures to share the same external interface. • Polymorphism is extensively used in implementing inheritance. Following concepts demonstrate different types of polymorphism in java. 1) Method Overloading 2) Method Overriding lecturer .miss .Ashna Nazm Hamasalh 31
  • 32. Method Overloading: In Java, it is possible to define two or more methods of same name in a class,provided that there argument list or parameters are different. This concept is known as Method Overloading. I have covered method overloading and Overriding below. To know more about polymorphism types refer my post Types of polymorphism in java: Stat ic, Dynamic, Runtime and Compile time Polymorphism. lecturer .miss .Ashna Nazm Hamasalh 32
  • 33. 1) Method Overloading 1. To call an overloaded method in Java, it is must to use the type and/or number of arguments to determine which version of the overloaded method to actually call. 2. Overloaded methods may have different return types; the return type alone is insufficient to distinguish two versions of a method. 3. 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. 4. It allows the user to achieve compile time polymorphism. 5. An overloaded method can throw different exceptions. 6. It can have different access modifiers. lecturer .miss .Ashna Nazm Hamasalh 33
  • 34. public static void main (String args []) { Overload Obj = new Overload(); double result; Obj .demo(10); Obj .demo(10, 20); }} Example: class Overload {void demo (int a){ System.out.println ("a: " + a); } void demo (int a, int b) { System.out.println ("a and b: " + a + "," + b); } double demo(double a) { System.out.println("double a: " + a); return a*a; }} lecturer .miss .Ashna Nazm Hamasalh 34
  • 35. Output: a: 10 a and b: 10,20 Here the method demo() is overloaded 3 times: first having 1 int paramete r,second one has 2 int parameters and third one is having double arg. The methodsare invoked or called with the same type and number of paramete rs used. lecturer .miss .Ashna Nazm Hamasalh 35
  • 36. Rules for Method Overloading 1. Overloading can take place in the same class or in its sub-class. 2. Constructor in Java can be overloaded 3. Overloaded methods must have a different argument list. 4. Overloaded method should always be the part of the same class (can also take place in sub class), with same name but different parameters. 5. The parameters may differ in their type or number, or in both. 6. They may have the same or different return types. 7. It is also known as compile time polymorphism. lecturer .miss .Ashna Nazm Hamasalh 36
  • 37. 2) Method Overriding Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. This feature is known as method overriding. lecturer .miss .Ashna Nazm Hamasalh 37
  • 38. Example: public class BaseClass { public void methodToOverride() //Base class method {System.out.println ("I'm the method of BaseClass"); }} lecturer .miss .Ashna Nazm Hamasalh 38 public class DerivedClass extends BaseClass { public void methodToOverride() //Derived Class method { System.out.println ("I'm the method of DerivedClass"); } }
  • 39. Output: I'm the method of BaseClass I'm the method of DerivedClass public class TestMethod{ public static void main (String args []) { // BaseClass reference and object BaseClass obj1 = new BaseClass(); // BaseClass reference but DerivedClass object BaseClass obj2 = new DerivedClass(); // Calls the method from BaseClass class obj1.methodToOverride(); //Calls the method from DerivedClass class obj2.methodToOverride();}} lecturer .miss .Ashna Nazm Hamasalh 39
  • 40. Rules for Method Overriding: 1. applies only to inherited methods 2. object type (NOT reference variable type) determines which overridden method will be used at runtime 3. Overriding method can have different return type (refer this) 4. Overriding method must not have more restrictive access modifier 5. Abstract methods must be overridden 6. Static and final methods cannot be overridden 7. Constructors cannot be overridden 8. It is also known as Runtime polymorphism. lecturer .miss .Ashna Nazm Hamasalh 40
  • 41. super keyword in Overriding: When invoking a superclass version of an overridden method the super keyword is used. lecturer .miss .Ashna Nazm Hamasalh 41
  • 42. Example: lecturer .miss .Ashna Nazm Hamasalh 42 class Vehicle { public void move () { System.out.println ("Vehicles are used for moving from one place to another");}} class Car extends Vehicle { public void move () { super. move (); // invokes the super class method System.out.println ("Car is a good medium of transport ");}} public class TestCar { public static void main (String args []){ Vehicle b = new Car (); // Vehicle reference but Car object b.move (); //Calls the method in Car class }}
  • 43. Output: Vehicles are used for moving from one place to another Car is a good medium of transport lecturer .miss .Ashna Nazm Hamasalh 43
  • 44. 44 lecturer .miss .Ashna Nazm Hamasalh