Inheritance and Polymorphism in java simple and clear
ashnanazm1
131 views
44 slides
Dec 08, 2021
Slide 1 of 44
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
About This Presentation
Inheritance and Polymorphism in java simple and clear with an example
Size: 715.56 KB
Language: en
Added: Dec 08, 2021
Slides: 44 pages
Slide Content
Lecturer :Ashna nazm hamasalh [email protected] 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 numbers:"+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 numbers:"+z); } } Child class parent class lecturer .miss .Ashna Nazm Hamasalh 15
After executing the program it will produce the following 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: Static, 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 parameter,second one has 2 int parameters and third one is having double arg. The methods are invoked or called with the same type and number of parameters 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