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

Chapter 3 - OOP For CS

ggggggge OOP for CS OOP for CS

Uploaded by

mate66960
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)
10 views

Chapter 3 - OOP For CS

ggggggge OOP for CS OOP for CS

Uploaded by

mate66960
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/ 44

Chapter Three

Inheritance & Polymorphism

By: Sinodos G
Inheritance

 The process where one class acquires the properties (methods and
fields) of another.
 Used to manage information 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).

extends Keyword class Super {


• extends is the keyword .....
.....
used to inherit the Syntax: }

properties of a class. class Sub extends Super {


.....
.....
}

2
Cont’d . . .

 It promotes code reusability and


 Allows a new class to extend [modify] functionality of an existing class.
• Code Reusability
• Subclass and Superclass Relationship
• Extending Functionality
• Single and Multiple Inheritance
• Access Control
• Method Overriding
• Abstract Classes and Interfaces
• Avoiding Code Duplication

3
Cont’d . . .

• 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.

4
Cont’d . . .

 The super keyword


 similar to this keyword. Used to:-
• differentiate the members of superclass from the
members of subclass, if they have same names.
• invoke the superclass constructor from subclass.

5
Cont’d . . .

Differentiate the members


• If a class is inheriting the
properties of another
class.
• if the members of the
superclass have the
names same as the sub
class, to differentiate these
variables we use super
keyword.
• Example
 super.variable;
 super.method();

6
Cont’d . . .

 Invoking Superclass Constructor


• If a class is inheriting the
properties of another class, the
subclass automatically
acquires the default
constructor of the superclass.
• But, to call a parameterized
constructor of the superclass,
you need to use the super
keyword

Example:
super(values);

7
IS-A Relationship
 IS-A is a way of saying: This object is a type of that object. Let us see how the extends
keyword is used to achieve inheritance.
public class Animal { • Animal is the superclass of Mammal class.
--- • Animal is the superclass of Reptile class.
} • Mammal and Reptile are subclasses of Animal
class.
public class Mammal extends Animal { • Dog is the subclass of both Mammal and Animal
--- classes.
}

public class Reptile extends Animal { the IS-A relationship, we can say −
---
} Mammal IS-A Animal
Reptile IS-A Animal
public class Dog extends Mammal { Dog IS-A Mammal
--- Hence: Dog IS-A Animal as well
}
8
Cont’d . . .

Output
true
true
true

9
Cont’d . . .

implements keyword
 used with classes to inherit the properties of an interface.
 Interfaces can never be extended by a class.

public interface Animal {


}
public class Mammal implements Animal {
}
public class Dog extends Mammal {
}

Instance Keyword
 Used to check and if a sub class is inherited from super class.
Example:
• it checks if Mammal is actually an Animal, and
• If dog is actually an Animal.
10
Cont’d . . .

11
Types of Inheritance
 Single Inheritance
• Occurs wen a class extends only one superclass

12
Cont’d . . .

 Multilevel Inheritance
• a subclass extends from a superclass and then the same subclass
acts as a superclass for another class.
• It achieves multiple inheritance through interfaces
• It allowing a class to implement multiple interfaces.

 Example:-

13
Example:

14
Hierarchical Inheritance
 When two or more classes inherits a single class, it is known as
hierarchical inheritance.
 Example: Dog and Cat classes inherits the Animal class

15
Cont’d . . .

 Multiple Inheritance
• Multiple inheritance is not supported in
java.
• Used to reduce the complexity and
simplify the language
• Example:
• Consider A, B, and C are three classes.
• The C class inherits A and B
classes.
• If A and B classes have the same
method and you call it from child
class object, there will be ambiguity
to call the method of A or B class. public class c extends A,B{}

16
Cont’d . . .

• Java doesn't support multiple


inheritance.

• However, we can achieve


multiple inheritance using
interfaces.

Example:
class Language extends
Frontend implements
Backend {

17
Cont’d . . .

 Hybrid Inheritance
• Hybrid inheritance is a combination of two or more types of inheritance.

Example:
public class Child extends HumanBody
implements Male, Female {}

18
Overriding
Overriding
• means to override the functionality of an existing method.
• If a class inherits a method from its superclass, then there is a
chance to override the method provided that it is not marked
final.

 Benefit of overriding
• ability to define a behavior that's specific to the subclass type,
which means a subclass can implement a parent class method
based on its requirement.

19
Cont’d . . .

20
Rules for Method Overriding
 The argument list should be exactly the same as that of the overridden
method.
 The return type should be the same or a subtype of the return type
declared in the original overridden method in the superclass.
 The access level cannot be more restrictive than the overridden
method's access level.
 For example: If the superclass method is declared public then the overridding
method in the sub class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the
subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.

21
Cont’d . . .

 A subclass within the same package as the instance's superclass can


override any superclass method that is not declared private or final.
 A subclass in a different package can only override the non-final
methods declared public or protected.
 An overriding method can throw any uncheck exceptions, regardless of
whether the overridden method throws exceptions or not. However, the
overriding method should not throw checked exceptions that are new or
broader than the ones declared by the overridden method.
 The overriding method can throw narrower or fewer exceptions than the
overridden method.
 Constructors cannot be overridden.

22
Cont’d . . .

super keyword
 When invoking a superclass version of an overridden method the
super keyword is used.
class Animal {
public void move() { public class TestDog {
public static void main(String args[]) {
System.out.println("Animals can move"); Animal b = new Dog();
} // Animal reference but Dog object
} b.move();
class Dog extends Animal { // runs the method in Dog class
public void move() { }}
super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
23
Cont’d . . .

Polymorphism
 the ability of an object to take on many forms.
 occurs when a parent class reference is used to refer to a child class
object.
 all Java objects are polymorphic since any object will pass the IS-A
test for their own type and for the class Object.
 Only possible to access an object through a reference variable.
 A reference variable
• Once declared cannot be changed.
• Can reassigned to other objects provided that it is not declared
final.
• A reference variable can be declared as a class or interface type.

24
Cont’d . . .

Example:
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

 Following are true for the above examples


Deer d = new Deer();
• A Deer IS-A Animal
Animal a = d;
• A Deer IS-A Vegetarian Vegetarian v = d;
• A Deer IS-A Deer Object o = d;
• A Deer IS-A Object
• All the reference variables d, a, v,
• Now, the Deer class is considered to be o refer to the same Deer object
polymorphic since this has multiple in the heap.
inheritance.
25
Cont’d . . .

 There are two types of polymorphism in Java:


 compile-time (static) polymorphism
 runtime (or dynamic) polymorphism.

 Compile-time Polymorphism: Example


 Method Overloading
class Calculator {
 occurs when two or more methods in the int add(int a, int b) {
same class have the same name but return a + b;
different parameters. }

 The compiler determines which method double add(double a, double b) {


to invoke based on the method signature. return a + b;
}
}

26
Cont’d . . .

 Runtime Polymorphism
 Method Overriding
 occurs when a subclass provides a specific implementation for a method
that is already defined in its superclass
Example:
cass Animal {
void makeSound() {
System.out.println("Generic animal sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
System.out.println("Bark! Bark!");
}
}
27
Abstraction
 The process of hiding certain details and showing only essential
information to the user.
 a process of hiding the implementation details and showing only
functionality to the user.
 Example:-
• Sending SMS where you type the text and send the message.
• You don't know the internal processing about the message delivery.
 Abstraction - focus on what the object does instead of how it does it.
 It can have abstract and non-abstract methods (method with the body).
Example:- public void get();
 There are two ways to achieve abstraction in java
• Abstract classes and
• Interfaces.
28
Abstract Class
 A class which is declared with
the abstract keyword is
known as an abstract class
 It can have abstract and non-
abstract methods.
 It needs to be extended and its
method implemented. It
cannot be instantiated.
 It can have constructors and
static methods also.
 It can have final methods
which will force the subclass
not to change the body of the
method.
29
Cont’d . . .

 If a class has at least one abstract method, then the class must be
declared abstract.
• If a class is declared abstract, it cannot be instantiated.
 To use an abstract class:-
• you have to inherit it from another class, provide implementations
to the abstract methods in it.
• If you inherit an abstract class, you have to provide
implementations to all the abstract methods in it.
 Abstraction promotes:-
• code reusability, Syntax:
• maintainability, and public abstract class
• flexibility in software development. Employee { }

30
Cont’d . . .

 Example:

31
Cont’d . . .

Features of Abstract Class • Template: presents the end-user with


a template that explains the methods
involved.
• Loose Coupling: Data abstraction in
Java enables loose coupling, by
reducing the dependencies at an
exponential level.
• Code Reusability: avoids the process
of writing the same code again.
• Abstraction: helps the developers
hide the code complications from the
end-user
• Dynamic Resolution: Using the
support of dynamic method resolution,
developers can solve multiple problems

32
Example 2

33
34
Abstract Methods
 A method which is declared as abstract and does not have
implementation is known as an abstract method.
 can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).
 Used If you want a class to contain a particular method but you want
the actual implementation of that method to be determined by child
classes, you can declare the method in the parent class as an
abstract.
• abstract keyword is used to declare the method as abstract.
• An abstract method contains a method signature, but no method
body.
• Instead of curly braces, an abstract method will have a
semoicolon (;)

35
Cont’d . . .

 An abstract class can have both abstract and regular methods:


abstract class Animal {
public abstract void animalSound();
public void sleep() {
System.out.println(“kjfkdfjdfjklfjZzz");
}
}
It is not possible to create an object of the Animal class:
Example:
Animal abj = new Animal(); // will generate an error
• To access the abstract class, it must be inherited from another class.

36
Example:
// Abstract class
abstract class Animal {
// Abstract method (does not have a body)
public abstract void animalSound();
// Regular method
public void sleep() {
System.out.println("ZzzQqq");
}
}
class Main {
// Subclass (inherit from Animal) public static void main(String[] args) {
class Pig extends Animal { Pig myPig = new Pig();
public void animalSound() { // Create a Pig object
// The body of animalSound() is provided here myPig.animalSound();
System.out.println("The pig says: wee wee"); myPig.sleep();
} }
} }

37
Example2

38
Interface
 a boundary between the method and the class implementing it.
 holds the method signature in it, but never the implementation.
 It is a fully abstract class and used to achieve abstraction.
 It includes a group of abstract methods (methods without a body).
 We use the interface keyword to create an interface
//Syntax:
interface <Class_Name>{
//Method_Signatures;
}

Example: interface Language {


public void getType();
public void getVersion();
}

39
Cont’d . . .

 Advantages of Interface
 To achieve security:
• hide certain details and only show the important details of an object
(interface).

 For multiple inheritance


• Java does not support "multiple inheritance" (a class can only inherit
from one superclass)
• However, it can be achieved with interfaces, because the class can
implement multiple interfaces.
• Note: To implement multiple interfaces, separate them with a comma

40
Implementing an Interface
 Like abstract classes:-
• we can’t create objects of interfaces.
• To use an interface, other classes must implement it.
• We use the implements keyword to implement an interface.

 On the implementation of an interface, you must override all of


its methods
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 An interface can’t contain a constructor (as it cannot be used to
create objects)

41
Example:

42
Multiple interface
• To implement multiple interfaces, separate them with a comma

43
Question

End of Chapter 3

Next  Chapter 4

44

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