OOP Chap 3 Deber Markose

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 47

Debre Markos University

Burie Campus
Department of Computer Science

Object Oriented programming

Lecture 3:
Inheritance and Polymorphism

Ayisheshim Almaw
ayishu165@gmail.com

1
outlines
Inheritance
Casting
Polymorphism
Method Overriding and Overloading
Super
The Object Class
Abstract Classes
Interfaces
Using Interfaces
Inheritance
• Inheritance in java is a mechanism in which one object acquires all the
properties and behaviours of another object.
• Inheritance provided mechanism that allowed a class to inherit property of
another class.
• When a Class extends another class it inherits all non-private members
including fields and methods
• Inheritance represents the IS-A relationship, also known as parent-
child relationship.
• extends keyword is used to describe inheritance in Java.

 As we can see in the image, a child inherits the


properties from his father. Similarly, in Java, there
are two classes:
 1. Parent class ( Super or Base class)
 2. Child class (Subclass or Derived class )
 A class which inherits the properties is known as
Child Class whereas a class whose properties are
inherited is known as Parent class.
Inheritance
• OOP allows classes to inherit commonly used state and behavior from
other classes.
• Rather than duplicating functionality, inheritance allows you to inherit
functionality from another class, called a superclass or base class.
• The idea of inheritance is simple but powerful:
 When you want to create a new class and there is already a class
that includes some of the code that you want, you can derive your
new class from the existing class.
 In doing this, you can reuse the fields and methods of the existing
class without having to write (and debug!) them yourself.
• Inheritance is one of the cornerstones of object-oriented programming
because it allows the creation of hierarchical classifications.

4
Why use inheritance in java
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}

Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritance (Not supported by java)
4. Hierarchical Inheritance
5. Hybrid Inheritance
Single Inheritance
• In single inheritance, one class inherits the properties of another.
• It enables a derived class to inherit the properties and behavior
from a single parent class.

Class A
{
---
}
Class B extends A {
---
}
Example:Single Inheritance
class Teacher {
void teach() {
System.out.println("Teaching subjects");
}}
class Students extends Teacher {
void listen() {
System.out.println("Listening to teacher");
}}
class CheckForInheritance {
public static void main(String args[]) {
Students s1 = new Students();
s1.teach();
s1.listen();
}}
Multilevel Inheritance:
• When a class is derived from a class which is also derived from
another class, i.e.
• a class having more than one parent class but at different levels,
such type of inheritance is called Multilevel Inheritance.
If we talk about the flowchart,
 class B inherits the properties and behavior of class A and
class C inherits the properties of class B.
 Here A is the parent class for B and class B is the parent
class for C.
 So in this case class C implicitly inherits the properties and
methods of class A along with Class B. That’s what is
multilevel inheritance.
Class A{
---
}
Class B extends A{
---
}
Class C extends B{
---
}
• Example : Multilevel Inheritance: class CheckForInheritance {
class Teacher { public static void main(String
void teach() { argu[]) {
homeTution h = new himeTution();
System.out.println("Teaching subject"); h.explains();
}} d.teach();
class Student extends Teacher { d.listen();
}
void listen() { }
System.out.println("Listening");
}}
class homeTution extends Student {
void explains() {
System.out.println("Does homework");
}}
Hierarchical inheritance

• When two or more derived class inherits the properties and


behavior from same parent class.
• It is known as hierarchical inheritance.
Class A{
---
}
Class B extends A{
---
}
Class C extends A{
---
}

If we talk about the flowchart,


 Class B and C are the child classes which are inheriting from the
parent class i.e Class A.
• Example: Hierarchical inheritance
class Teacher {
void teach() {
System.out.println("Teaching subject");
}}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}}
class CheckForInheritance {
class Principal extends Teacher { public static void main(String argu[])
void evaluate() { {
System.out.println("Evaluating"); Principal p = new Principal();
}} p.evaluate();
p.teach();
// p.listen(); //will produce an error
}
}
Why multiple inheritance is not supported in Java?
• To remove ambiguity.
• To provide more maintainable and clear design.

 Private members do NOT get inherited.


 Constructors cannot be Inherited in Java.
super keyword

• Super is a keyword of Java which refers to the immediate parent of a


class and is used inside the subclass method definition for calling a
method defined in the superclass.
• Usage of java super Keyword
 super is used to refer immediate parent class instance variable.
 super() is used to invoke immediate parent class constructor.
 super is used to invoke immediate parent class method.
Super at Variable level
• Whenever we inherit the base class members into derived class, there is a
possibility that base class members are similar to derived class members.
• In order to distinguish the base class members with derived class
members in the derived class, the base class members will be preceded
by a keyword super.
• Syntax super. base class member name
• Example for Super at Variable level
class Parent {
String name;
}
public class Child extends Parent {
String name;
public void details() {
super.name = "Parent"; //refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
Super at Method level
 Whenever we inherit the base class methods into the derived class, there is a
possibility that base class methods are similar to derived methods.
 To differentiate the base class methods with derived class methods in the derived
class, the base class methods must be preceded by a keyword super.
 Syntax : super. base class method name
class Animal { // Superclass (parent)
public void animalSound() {
System.out.println("The animal makes a sound");
}}
class Dog extends Animal { // Subclass (child)
public void animalSound() {
super.animalSound(); // Call the superclass method
System.out.println("The dog says: bow wow");
}}
public class Main {
public static void main(String[] args) {
Animal myDog = new Dog(); // Create a Dog object
myDog.animalSound(); // Call the method on the Dog object
}}
super is used to invoke parent class constructor.
• The super keyword can also be used to invoke the
parent class constructor as given below:
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike5 extends Vehicle{
Bike5(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike5 b=new Bike5();
Final keyword
• Final is a keyword in Java that is used to restrict the user and can
be used in many respects.
• Final can be used with:
• Class
• Methods
• Variables
• When a class is declared as final, it cannot be extended further.
• A method declared as final cannot be overridden; this means
even when a child class can call the final method of parent class
without any issues, but the overriding will not be possible.
• Once a variable is assigned with the keyword final, it always
contains the same exact value
Final variable

• If we declare a variable as final then


it prevents its content from being modified. The variable acts like
a constant. Final field must be initialized when it is declared.
• Example:
public class Test {

final int a = 10;


public static void main(String[] args) {
Test test = new Test();
test.a = 15; // compile error
System.out.println("a = "+test.a);
}}
Final Method
• A method which is declared using final keyword known as final method. It is
useful when we want to prevent a method from overridden.
class A {
final void display() {
System.out.println("This is a final method.");
}
}
class B extends A {
void display() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
• Because display( ) is declared as final, it cannot be overridden in
B. If you attempt to do so, a compile-time error will result.
19
• final method is inherited but you cannot override it.
Final Class / Using final to Prevent Inheritance
• Sometimes you will want to prevent a class from being inherited.
To do this, precede the class declaration with final.
• Declaring a class as final implicitly declares all of its methods as
final, too.
final class ABC{
int a = 10;
void show() {
System.out.println("a = "+a);
}}
public class BC extends ABC{

public static void main(String[] args) {


The type BC cannot subclass the final class ABC
BC demo = new BC();
20
}}
Casting
• Casting is a process of changing one type value to another type.
• In Java, we can cast one type of value to another type. It is
known as type casting.
• In Java, type casting is classified into two types,
A. Widening Casting(Implicit)

B. Narrowing Casting(Explicitly done)


Widening or Automatic type converion
• Automatic Type casting take place when,
– the two types are compatible
– the target type is larger than the source type
public class Test
{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}}
Narrowing or Explicit type conversion

• When you are assigning a larger type value to a variable of smaller


type, then you need to perform explicit type casting.
• If we don't perform casting then compiler reports compile time error.
public class Test
{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}}
Method Overloading
• Method overloading is a concept that allows to declare multiple
methods with same name but different parameters in the same
class.
• Method overloading is one of the ways through which java supports
polymorphism.
• There are different ways to overload a method in Java. They are:
o Based on the number of parameters: In this case, the entire
overloading concept depends on the number of parameters that are
placed within the parenthesis of the method.
o Based on the data type of the parameter: With the arrangement of data
type, within the parameter, overloading of the method can take place.
o Based on the sequence of data types in parameters: The method
overloading also depends on the ordering of data types of parameters
within the method.
• Note: method overloading is not possible by changing the return
type of the method because there may arise some ambiguity.
• Method overloading by changing data type of arguments.
• Example
we have two sum() methods that take integer
class Calculate { and float type arguments respectively
void sum (int a, int b) {
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b) {
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args) {
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}}
Method overloading Based on the sequence of data types
in parameters: Example:
• In this scenario, method overloading works but internally
JVM treat it as method having different type of arguments

class Demo{
public void get(String name, int id)
System.out.println("Id is :"+ id);
{
System.out.println("Name is :"+ name);
System.out.println(“Name is :"+ name); }}
System.out.println(" Id is :"+ id); class MethodDemo8{
} public static void main (String[] args) {
Demo obj = new Demo();
public void get(int id, String name) obj.get(“Ayishu", 1);
{ obj.get(“Almaw", 2);
}}
 In Java, we can overload the main() method using different number and types
of parameter but the JVM only understand the original main() method.
Method Overriding in Java

• Method overriding is a process of overriding base class method by


derived class method with more specific definition.
• Method overriding performs only if two classes have is-a relationship.
• It mean class must have inheritance. In other words, It is performed
between two classes using inheritance relation.
• In overriding, method of both class must have same name and equal
number of parameters.
• Method overriding is also referred to as runtime
polymorphism because calling method is decided by JVM during
runtime.
• The key benefit of overriding is the ability to define method that's
specific to a particular subclass type.
• Rules for Method Overriding
1. Method name must be same for both parent and child classes.
2. Access modifier of child method must not restrictive than parent class
method.
3. Private, final and static methods cannot be overridden.
4. There must be an IS-A relationship between classes (inheritance).
class Animal{
public void eat() {
System.out.println("Eat all eatables");
}}
class Dog extends Animal {
public void eat() //eat() method overridden by Dog class.
{
System.out.println("Dog like to eat meat");
}
Can we
public static void main(String[] Override
args) { static method? Explain with reasons?
Dog d = new Dog(); No, we cannot override static method. Because static
method is bound to class whereas method overriding is
d.eat();
associated with object
}}
Method Overloading Method Overriding
Parameter must be different and name must be Both name and parameter must be same.
same.
Compile time polymorphism. Runtime polymorphism.
Increase readability of code. Increase reusability of code.
Access specifier can be changed. Access specifier cannot be more restrictive than
original method(can be less restrictive).
It is Compiled Time Polymorphism. It is Run Time Polymorphism.
It is performed within a class It is performed between two classes using inheritance
relation.
It is performed between two classes using It requires always inheritance.
inheritance relation.
It should have methods with the same name but It should have methods with same name and
a different signature. signature.
It can not have the same return type. It should always have the same return type.
It can be performed using the static method It can not be performed using the static method
It uses static binding It uses the dynamic binding.
Access modifiers and Non-access modifiers can Access modifiers and Non-access modifiers can not be
be changed. changed.
It is code refinement technique. It is a code replacement technique.
No keywords are used while defining the Virtual keyword is used in the base class and overrides
method. keyword is used in the derived class.
Private, static, final methods can be overloaded Private, static, final methods can not be overloaded
polymorphism
• In java polymorphism is a way in which something behaves
differently based on its call.
• Polymorphism in java is a concept by which we can perform
a single action by 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.
• Types of polymorphism:
1. Static/compile time polymorphism (by method overloading).
2. Dynamic/run time polymorphism (by method overriding).
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.
• In this process, an overridden method is called through the
reference variable of a superclass

Upcasting in Java
 When Parent class reference
variable refers to Child class
object, it is known as
Upcasting.

Q. What is the difference between Static


binding and Dynamic binding in Java explain
with example?
Object class in Java

• The Object class is the parent class of all the classes in java by
default. In other words, it is the topmost class of java.
• The Object class is beneficial if you want to refer any object whose
type you don't know.
• Let's take an example, there is getObject() method that returns an
object but it can be of any type like Employee,Student etc, we can
use Object class reference to refer that object. For example:
• Object obj=getObject();//we don't what object would be returned
from this method
• The Object class provides some common behaviours to all the
objects such as object can be compared, object can be cloned,
object can be notified etc.
Abstraction
• Abstraction is a process of hiding the implementation details
and showing only functionality to the user. Or
• show only important things to the user and hides the internal
details.
• for example sending sms, you just type the text and send the
message. You don't know the internal processing about the
message delivery.
• Abstract way to show essential details (what) to the user and hide non-
essential details (how).
• Advantages/Benefits of Abstraction:
– Only show essential details to end user.
– Hide complexity.
• There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
Abstract Classes and Methods

• The abstract keyword is a non-access modifier, used for classes


and methods:
• A class which is declared using abstract keyword known
as abstract class.
• Abstract class: is a restricted class that cannot be used to create
objects (to access it, it must be inherited from another class).
• Syntax:
abstract class class_name { }
• Abstract method: Method that are declared without any body
within an abstract class . Hence The body is provided by the
subclass (inherited from).
• An abstract class can have both abstract and regular methods:
• Syntax:
– abstract return_type function_name (); //No definition
• Points to Remember about Abstract Class and
Method
 If a class have one abstract method it must be an abstract class
but vice versa is not true i.e. it is not necessary that an abstract
class have an abstract method.
 Abstract classes can have Constructors, Member variables and
Normal methods.
 Abstract classes are never instantiated.
 When you extend Abstract class with abstract method, you must
define the abstract method in the child class, or make the child
class abstract.
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("Zzz");
}}
// Subclass (inherit from Animal)
class Pig extends Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The pig says: wee wee");
}}
class Main {
public static void main(String[] args) {
Pig myPig = new Pig(); // Create a Pig object
myPig.animalSound(); Note: Animal myObj = new Animal(); // will generate an error
myPig.sleep();
Interface in Java

• Let us take example of a TV real example. You press change channel button of TV remote
and channel is changed. Here remote acts as an interface between you and TV.
• An interface is a collection of abstract methods.
• The interface in java is a mechanism to achieve fully abstraction
• Interfaces are syntactically similar to classes, but you cannot create instance of
an Interface and their methods are declared without any body.
• Advantages of Interface
– It Support multiple inheritance
– It helps to achieve abstraction
• When an interface inherits another interface extends keyword is used whereas class
use implements keyword to inherit an interface.

 a class extends another class, an


interface extends another
interface but a class
implements an interface
Interfaces(cont)
• An interface is similar to a class in the following ways:
1. An interface can contain any number of methods.
2. An interface is written in a file with a .java extension, with the
name of the interface matching the name of the file.
3. The bytecode of an interface appears in a .class file.
• However, an interface is different from a class in several ways,
including:
1. You cannot instantiate an interface.
2. An interface does not contain any constructors.
3. All of the methods in an interface are abstract.
4. An interface cannot contain instance fields. The only fields that
can appear in an interface must be declared both static and final.
5. An interface is not extended by a class; it is implemented by a
class.
6. An interface can extend multiple interfaces. 39
Declaring Interfaces
• The interface keyword is used to declare an interface.
• Access to the data and code is tightly controlled by an interface.
• Let us look at an example
public interface NameOfInterface {
//Any number of final, static fields
//Any number of abstract method declarations
}
• Interfaces have the following properties:
– An interface is implicitly abstract. You do not need to use
the abstract keyword when declaring an interface.
– Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.
– Methods in an interface are implicitly public.
40
Implementing Interfaces
• When a class implements an interface, you can think of the class as
signing a contract, agreeing to perform the specific behaviors of
the interface.
• If a class does not perform all the behaviors of the interface, the
class must declare itself as abstract.
• A class uses the implements keyword to implement an interface.
• Implementing an interface allows a class to become more formal
about the behavior it promises to provide.
• Interfaces form a contract between the class and the outside world,
and this contract is enforced at build time by the compiler.
• If your class claims to implement an interface, all methods defined
by that interface must appear in its source code before the class will
successfully compile.

41
• The general form of a class that includes the implements clause looks
like this:
modifier class classname [extends superclass] [implements interface
[interface...]
{
// class-body
}
• Here, modifier is either public or not used.
• If a class implements more than one interface, the interfaces are
separated with a comma.
• If a class implements two interfaces that declare the same method, then
the same method will be used by clients of either interface.
• The methods that implement an interface must be declared public.
• Also, the type signature of the implementing method must match
exactly the type signature specified in the interface definition.

42
// Interface
interface Animal {
public void animalSound(); // interface method (does not have a body)
public void sleep(); // interface method (does not have a body)
}
// Cat "implements" the Animal interface
class Cat implements Animal {
public void animalSound() {
// The body of animalSound() is provided here
System.out.println("The Cat says: meew meew");
}
public void sleep() { class Main {
public static void main(String[] args) {
// The body of sleep() is provided here
Cat my Cat = new Cat(); // Create a Pig
System.out.println("Zzz"); object
}} my Cat.animalSound();
my Cat.sleep();
}}
Extending Interfaces
• An interface can extend another interface, similarly to the way
that a class can extend another class.
• The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.
• The following Sports interface is extended by Hockey and
Football interfaces.
Extending Multiple Interfaces:
• A Java class can only extend one parent class. Multiple
inheritance is not allowed. Interfaces are not classes, however,
and an interface can extend more than one parent interface.
• The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.
• For example, if the Hockey interface extended both Sports and
Event, it would be declared as:
public interface Hockey extends Sports, Event 44
Multiple inheritance in Java by interface
• If a class implements multiple interfaces, or an interface extends
multiple interfaces i.e. known as multiple inheritance.

interface Printable { public void show(){


void print(); System.out.println("Welcome");}
} public static void main(String args[]){
interface Showable{ A7 obj = new A7();
void show(); obj.print();
} obj.show();
class A7 implements Printable,Showable{ }
public void print() }
{System.out.println("Hello");}
What is the difference between a Class and an Interface?
• A class and an interface are two different types (conceptually).

• Theoretically a class emphasis the idea of encapsulation, while


an interface emphasis the idea of abstraction (by suppressing the
details of the implementation). The two poses a clear separation
from one to another.

• A class can be defined to implement an interface and also it


supports multiple implementations. When a class implements
an interface, an object of such class can be encapsulated inside
an interface.

46
• End of Ch.3
Questions, Ambiguities, Doubts, … ???

You might also like