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

OOP Chapter III-1

Uploaded by

abrhamashenafi3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

OOP Chapter III-1

Uploaded by

abrhamashenafi3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Wolaita Sodo University

School of Informatics
Department of Computer Science

Chapter 3: Inheritance and Polymorphism

Compiled by Dawit Uta. (M. Tech.)


Computer Science Department, WSU
website address: www.davidtechnotips.com
Chapter 3: Inheritance and Polymorphism
2

3.1.Inheritance
3.2.Casting
3.3. Polymorphism
3.4. Method Overriding and Overloading
3.5.Super
3.6.The Object Class
3.7.Abstract Classes
3.8.Interfaces
3.9.Using Interfaces
3.1.Inheritance
3

 Inheritance is one of the cornerstones of object-oriented programming because it


allows the creation of hierarchical classifications.
 Using inheritance, you can create a general class that defines traits common to a set of
related items.
 This class can then be inherited by other, more specific classes, each adding those
things that are unique to it.
 In the terminology of Java, a class that is inherited is called a superclass. The class that
does the inheriting is called a subclass.
 Therefore, a subclass is a specialized version of a superclass. It inherits all of the
instance variables and methods defined by the superclass and adds its own, unique
elements.
3.1.Inheritance cont…
4 Superclass Subclasses
Student GraduateStudent, UndergraduateStudent
Shape Circle, Triangle, Rectangle
Loan CarLoan, HomeImprovementLoan, MortgageLoan
Employee Faculty, Staff, AcademicStaff, AdminStaff
BankAccount CreditAccount, SavingsAccount
Fig. 3.1 Inheritance examples
5 Inheritance Basics
 To inherit a class, you simply incorporate the definition of one class into another by
using the extends keyword. To see how, let’s begin with a short example. The following
program creates a superclass called A and a subclass called B. Notice how the
keyword extends is used to create a subclass of A. class B extends A {
// A simple example of inheritance. int k;
class A {// Create a superclass. void showk() {
int i, j; System.out.println("k: " + k);
void showij() { }
System.out.println("i and j: " + i + " " + j); void sum() {
} System.out.println("i+j+k: " + (i+j+k));
}//closing showij() method }
// Create a subclass by extending class A. }
/* The subclass has access to all public members
6
of its superclass. */
subOb.i = 7;
class SimpleInheritance {
subOb.j = 8;
public static void main(String args[]) {
subOb.k = 9;
A superOb = new A();
System.out.println("Contents of subOb: ");
B subOb = new B();
subOb.showij();
// The superclass may be used by itself.
subOb.showk();
superOb.i = 10;
System.out.println();
superOb.j = 20;
System.out.println("Sum of i, j and k in subOb:");
System.out.println("Contents of superOb: ");
subOb.sum(); output
superOb.showij();
}
System.out.println();
}
7

 As you can see, the subclass B includes all of the members of its superclass, A. This is why
subOb can access i and j and call showij( ).
 Also, inside sum( ), i and j can be referred to directly, as if they were part of B.
 Even though A is a superclass for B, it is also a completely independent, stand-alone class.
 Being a superclass for a subclass does not mean that the superclass cannot be used by itself.
Further, a subclass can be a superclass for another subclass.

The general form of a class declaration that inherits a superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
8 Type Casting in Java
 In Java, type casting is a method or process that converts a one data type into another data
type in both ways manually and automatically.
 The automatic conversion is done by the compiler and manual conversion performed by the
programmer.
 Type casting and its types in the diagram.
9

 Narrowing Type Casting: converting a higher data type into a lower one. It is also
known as explicit conversion or casting up.
 It is done manually by the programmer. If we do not perform casting then the compiler
reports a compile-time error.
10

public class NarrowingTypeCasting {


public static void main(String args[]) {
double d = 12.76;
Output
//converting double data type into long data type
Before conversion: 12.76
long l = (long)d;
After conversion into long type: 12
//converting long data type into int data type
After conversion into int type: 12
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
11

 Widening Type Casting: converting a lower data type into a higher one. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is
no chance to lose data. It takes place when:
 Both data types must be compatible with each other.
 The target type must be larger than the source type.

For example, the conversion between numeric data type to char or Boolean is not done
automatically.
Also, the char and Boolean data types are not compatible with each other.
Example:
12 public class WideningTypeCasting {
public static void main(String[] args) {
int x = 8;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
} output
Before conversion, the value is: 8
After conversion, the long value is: 8
After conversion, the float value is: 8.0
13 Polymorphism
 Polymorphism in Java is a concept by which we can perform a single action in different
ways. Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly"
means many and "morphs" means forms. So polymorphism means many forms.
 There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
 If you overload a static method in Java, it is the example of compile time polymorphism.
Here, we will focus on runtime polymorphism in java.
 Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
14
Method Overriding and Overloading
 If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
 In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 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).
15

 A real example of Java Method Overriding


 Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, Awash,
CBE and NIB banks could provide 8%, 7%, and 9% rate of interest.
16
//Java Program to demonstrate the real scenario of Java Method Overriding
//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
//Test class to create objects and call the methods
int getRateOfInterest(){return 0;}
class Test2{
}
public static void main(String args[]){
//Creating child classes.
Awash a=new Awash();
class Awash extends Bank{
CBE c=new CBE();
int getRateOfInterest(){return 8;}
NIB n=new NIB();
}
System.out.println(“Awash Rate of Interest: "+a.getRateOfInterest());
class CBE extends Bank{ System.out.println(“CBE Rate of Interest: "+c.getRateOfInterest());
int getRateOfInterest(){return 7;}
} System.out.println(“NIB Rate of Interest: "+n.getRateOfInterest());
class NIB extends Bank{ } Output:
int getRateOfInterest() { Awash Rate of Interest: 8
}
return 9; CBE Rate of Interest: 7
} } NIB Rate of Interest: 9
17 Method Overloading in Java
 If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
 If we have to perform only one operation, having same name of the methods increases the
readability of the program.
 Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int)
for three parameters then it may be difficult for you as well as other programmers to
understand the behavior of the method because its name differs.
 So, we perform method overloading to figure out the program quickly.
 There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
1. By changing number of arguments: in this example, we have created two
18 methods, first add() method performs addition of two numbers and second add
method performs addition of three numbers.
 Here we are creating static methods so that we don't need to create instance for
Example:
calling methods.
class Adder{
static int add(int a,int b){
return a+b;} Output
static int add(int a,int b,int c){ 22
return a+b+c;} 33
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(10,12));
System.out.println(Adder.add(10,11,12));
}
}
19 2) Method Overloading: changing data type of arguments
 In this example, we have created two methods that differs in data type.
 The first add method receives two integer arguments and second add method receives two
double arguments.
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{ Output
public static void main(String[] args){ 22
System.out.println(Adder.add(10,12)); 24.0
System.out.println(Adder.add(11.5,12.5));
}
}
Difference between method overloading and method
20 overriding in java
No Method Overloading Method Overriding
1)  Method overloading is used to increase the  Method overriding is used to provide the specific
readability of the program. implementation of the method that is already
provided by its super class.
2)  Method overloading is performed within class.  Method overriding occurs in two classes that have
IS-A (inheritance) relationship.
3)  In case of method overloading, parameter must be  In case of method overriding, parameter must be
different. same.
4)  Method overloading is the example of compile time  Method overriding is the example of run time
polymorphism. polymorphism.
5)  In java, method overloading can't be performed by  Return type must be same or covariant in method
changing return type of the method only. Return type overriding.
can be same or different in method overloading. But
you must have to change the parameter.
21 super
 The super keyword refers to superclass (parent) objects.
 It is used to call superclass methods, and to access the superclass members.
 The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
class Animal{ class TestSuper1{
String color="white"; public static void main(String args[]){
} Dog d=new Dog();
class Dog extends Animal{ d.printColor();
String color="black"; }
void printColor(){ }
System.out.println(color);//prints color of Dog class Output
System.out.println(super.color);//prints color of Animal class black
} white
super
22

 In the above example, Animal and Dog both classes have a common property color. If
we print color property, it will print the color of current class by default.
 To access the parent property, we need to use super keyword.
Abstract class
23

 A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).
 The major use of abstract classes and methods is to achieve abstraction in Java.
 Abstraction is an important concept of object-oriented programming that allows us to hide
unnecessary details and only showing functionality to the user.
 This allows us to manage complexity by omitting or hiding details with a simpler, higher-
level idea.
 A practical example of abstraction can be motorbike brakes. We know what brake does.
When we apply the brake, the motorbike will stop. However, the working of the brake is
kept hidden from us.
 The major advantage of hiding the working of the brake is that now the manufacturer can
implement brake differently for different motorbikes, however, what brake does will be the
same. Another example, sending SMS where you type the text and send the message. You
don't know the internal processing about the message delivery.
24

 There are two ways to achieve abstraction in java


 Abstract class (0 to 100%)
 Interface (100%)
Abstract class in Java
abstract class A{}
25
 Abstract Method in Java
 A method which is declared as abstract and does not have implementation is known as
an abstract method. abstract void printStatus();//no method body and abstract
abstract class Bike{ Bike is an abstract class that contains only one
abstract void run(); abstract method run. Its implementation is
} provided by the Yamaha class
class Yamaha extends Bike{
void run(){ System.out.println("running safely");
}
public static void main(String args[]){
Bike obj = new Yamaha();
obj.run(); Output
} running safely
}
Interface in Java
26
 An interface in Java is a blueprint of a class. It has static constants and abstract methods.
 The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body.
 It is used to achieve abstraction and multiple inheritance in Java.
 In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
 Java Interface also represents the IS-A relationship
The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.
27

interface A{ class Test{


void a(); public static void main(String args[]){
void b(); A a=new M();
void c(); a.a();
void d(); a.b();
} a.c();
abstract class B implements A{ a.d();
public void c(){System.out.println("I am c");} }
} }
class M extends B{
public void a(){System.out.println("I am a");} Output:
public void b(){System.out.println("I am b");} I am a
public void d(){System.out.println("I am d");} I am b
} I am c
I am d
28 summarizing

 We use the abstract keyword to create abstract classes and methods.


 An abstract method doesn't have any implementation (method body).
 A class containing abstract methods should also be abstract.
 We cannot create objects of an abstract class.
 To implement features of an abstract class, we inherit subclasses from it and create
objects of the subclass.
 A subclass must override all abstract methods of an abstract class. However, if the
subclass is declared abstract, it's not mandatory to override abstract methods.
 We can access the static attributes and methods of an abstract class using the reference
of the abstract class

The end of chapter 3

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy