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

(OOP) Chapter 3

The document discusses key concepts of Object Oriented Programming (OOP), including inheritance, polymorphism, abstraction, and encapsulation. [1] It provides examples to explain inheritance in OOP using classes like Animal, Dog, and Cat, showing how subclasses inherit properties from parent classes to avoid duplicating code. [2] Polymorphism allows objects to act differently depending on their runtime type through method overloading and overriding. Method binding can occur at compile-time or runtime. [3] Abstraction in OOP involves hiding implementation details and exposing only essential functions to the user.

Uploaded by

birhanu gebisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views

(OOP) Chapter 3

The document discusses key concepts of Object Oriented Programming (OOP), including inheritance, polymorphism, abstraction, and encapsulation. [1] It provides examples to explain inheritance in OOP using classes like Animal, Dog, and Cat, showing how subclasses inherit properties from parent classes to avoid duplicating code. [2] Polymorphism allows objects to act differently depending on their runtime type through method overloading and overriding. Method binding can occur at compile-time or runtime. [3] Abstraction in OOP involves hiding implementation details and exposing only essential functions to the user.

Uploaded by

birhanu gebisa
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Introduction

The Objects Oriented Programming (OOP) is constructed


over four major principles:
-- > Inheritance
-- > Polymorphism
-- > Abstraction
-- > Encapsulation
Inheritance
What is Inheritance?
 In the real world: We inherit traits from our mother and
father. We also inherit traits from our grandmother, grandfather, and
ancestors. We might have similar eyes, the same smile, a different
height . . . but we are in many ways "derived" from our parents.
 In software: Object inheritance is more well defined. Objects that are
derived from other object "resemble” their parents by inheriting both
state (fields) and behavior(methods).
Cont..
 Inheritance is a fundamental feature of object-oriented
programming which enables the programmer to write a class based on
an already existing class.
 The already existing class is called the parent class, or super-class,
and the new class is called the subclass, or derived class.
 The subclass inherits (reuses) the non-private members (methods
and variables) of the super-class, and may define its own members as
well.
 Inheritance is implemented in Java using the keyword extends.
 When class B is a subclass of class A, we say B extends A.
Cont..
Advantages of Inheritance.
Code reusability:- Inheritance automates the process of reusing the
code of the superclasses in the subclasses.
>> With inheritance, an object can inherit its more general properties
from its parent object, and that saves the redundancy in programming.
Code maintenance:- Organizing code into hierarchical classes makes
its maintenance and management easier.
Implementing OOP:- Inheritance helps to implement the basic OOP
philosophy to adapt computing to the problem and not the other way
around, because entities (objects) in the real world are often organized
into a hierarchy.
Cont..
Inheritance Types
A. Single level inheritance:- Inheritance in which a class inherits from only one super
class.
B. Multi-level inheritance:- Inheritance in which a class inherits from a class which
itself inherits from another class. Here a minimum of three classes is required.
C. Hierarchy inheritance:- Here two or more classes inherits from one class.
D. Multiple inheritance:- A class inherits from two or more classes. This type of
inheritance is not supported in Java. [achieved Using interfaces.]
E. Hybrid Inheritance: In simple terms you can say that Hybrid inheritance is a
combination of Single and Multiple inheritance. A typical flow diagram would look
like below. A hybrid inheritance can be achieved in the java in a same way as
multiple inheritance can be!! Using interfaces.
Cont..
Consider the following example
//Dog Class

public class Dog {


private String name;
private int fleas;
public Dog(String n, int f) {
name = n;
fleas = f;
}
public String getName() { return name; }
public int getFleas() { return fleas; }
public void speak() {
System.out.println("Woof");
}}
Cont..
//Cat Class
public class Cat {
private String name;
private int hairballs;
public Cat(String n, int h) {
name = n;
hairballs = h;
}
public String getName() { return name; }
public int getHairballs() { return hairballs; }
public void speak() {
System.out.println("Meow");
}
}
Cont..
Problem: Code Duplication
Dog and Cat have the name field and the getName()
method in common
 Classes often have a lot of state and behavior in common
Result: lots of duplicate code!
Solution: Inheritance
 Inheritance allows you to write new classes that inherit from existing classes
 The existing class whose properties are inherited is called the "parent" or super-class
 The new class that inherits from the super class is called the "child" or subclass
Result: Lots of code reuse!
Cont..
Cont..
//Animal Super-class //Dog Subclass

public class Animal { public class Dog extends Animal {

String name; private int fleas;

public Animal(String n) { public Dog(String n, int f) {

name = n; super(n); // calls Animal constructor

} fleas = f;

public String getName() { }

return name; public int getFleas() {

} return fleas;

} }
public void speak() {
return System.out.println("Woof");
}}
Cont..
//Cat Subclass
public class Cat extends Animal {
private int hairballs;
public Cat(String n, int h) {
super(n); // calls Animal constructor
hairballs = h;
}
public int getHairballs() {
return hairballs;
}
public void speak() {
return System.out.println("Meow");
}
}
Cont..
Inheritance Quiz 1
What is the output of the following?
Dog d = new Dog("Rover" 3);
Cat c = new Cat("Kitty", 2);
System.out.println (d.getName() + " has " +d.getFleas() + " fleas");
System.out.println (c.getName() + " has " +c.getHairballs() + " hairballs");

//Outputs
============
Rover has 3 fleas
Kitty has 2 hairballs

(Dog and Cat inherit the getName method from Animal)


Cont..
Inheritance Rules
 Use the extends keyword to indicate that one class inherits from
another
The subclass inherits all the non-private fields and methods of the
super-class
 Use the super keyword in the subclass constructor to call the super-
class constructor.
Cont..
Subclass Constructor
 The first thing a subclass constructor must do is call the super-class
constructor.
 This ensures that the super-class part of the object-is constructed
before the subclass part.
 If you do not call the super-class constructor with the super keyword,
and the super-class has a constructor with no arguments, then that
super-class constructor will-be called implicitly.
Cont..
Implicit Super Constructor Call //then this Beef subclass:

//If I have this Food class: public class Beef extends Food {
private double weight;
public Beef(double w) {
public class Food {
weight = w
boolean raw; 1
}
boolean raw;
//is equivalent to:
public Food() {
public class Beef extends Food {
raw = true;
private double weight;
}}}}
public Beef(double w) { 2
super();
weight = w
}} 3
Cont..
Inheritance Quiz 2
public class A {
public A() { System.out.println("I'm A"); }
} // outputs

public class B extends A { ==========


I'm A
public B() { System.out.println("I'm B"); }
I'm B
}
I'm C
public class C extends B {
public C() { System.out.println("I'm C"); }
}
What does this print out?
C x = new C();
Polymorphism
 Polymorphism is one of the principles in Object Oriented Programming
paradigm.
 The term polymorphism means “a method the same as another in spelling
but with different behavior.”
 Polymorphism is the ability of objects to act depending on the run time
type.
 Polymorphism allows programmers to send the same message to objects
from different classes. i.e., in its simplest from, polymorphism allows a
single variable to refer to objects from different classes.
 Polymorphism enables us to “program in the general” rather than
“program in the specific”.
Method binding
 In general, connecting a method call to a method body is called binding.

 When binding is performed before the program is run, it’s called early
binding. also called [static binding] OR [compile-time binding]

 When the binding occurs at run-time based on the type of object, it’s
called late binding. also called [dynamic binding] OR [run-time binding.]

 When late binding is implemented, there must be some mechanism to


determine the type of the object at run-time and to call the appropriate
method.

 That is, the compiler still doesn’t know the object type, but the method-
call mechanism finds out and calls the correct method body.
Implementation of method binding
(Polymorphism)
 Method Overloading (Early Binding) static binding
 Methods with same name, but the compiler uses two mechanisms to
differentiate the overloaded methods
 Number of parameters
 Datatype of parameters

 Method Overriding (Late Binding) dynamic binding


 Methods with same name and signature and applied on inheritance concepts.
 Methods of a subclass override the methods of a super class in a given
inheritance hierarchy.
 Methods of a subclass implement the abstract methods of an abstract class.
 Methods of a concrete class implement the methods of an interface.
Overloading: sample code
Overriding: sample code
Abstraction
Abstraction [dictionary meaning]-is the quality of dealing with ideas
rather than events.
 In object oriented programming abstraction is a process of hiding
the implementation details from the user, only the functionality will
be provided to the user.
 In other words user will have the information on what the object
does instead of how it does.
 In Java Abstraction is achieved using Abstract classes, Abstract
methods and Interfaces.
Cont..
Abstract Methods
 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 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 semicolon ( ; )
at the end.
Syntax: <access specifier> abstract <return type><methodName>(para_list);
Example: public abstract void calculateArea();
Cont..
Abstract Class
 A class which contains the abstract keyword in its declaration is known as
abstract class.
 Abstract classes may or may not contain abstract methods [methods with
out body ( public void get(); )] –only declaration of a method.
 But, if a class have at least one abstract method, then the class must be
declared as abstract.
 Abstract classes cannot be instantiated(cannot create object).
 If you inherit an abstract class you have to provide implementations to all
the abstract methods in it.
Syntax: <access specifier> abstract class <className>{ // code inside of the class }
Example: public abstract class Shape { // code inside of the class }
Cont..
 Suppose we were modeling the behavior of animals, by creating a class
hierarchy that started with a base class called Animal.
 Animals are capable of doing different things like flying, digging and
walking, but there are some common operations as well like eating and
sleeping.
 Some common operations are performed by all animals, but in a different
way as well.
 When an operation is performed in a different way, it is a good candidate
for an abstract method (forcing subclasses to provide a custom
implementation).
 Let's look at a very primitive Animal base class, which defines an abstract
method for making a sound (such as a dog barking, a cow mooing etc.).
Cont..
public abstract Class Animal { public class Cat extends Animal{

public void eat(String fd) { //implementation of abstract method


void makeNoise()
// do something
{
}
System.out.print(“meow”);
public void sleep(int hours) { }}
// do something public class Dog extends Animal{

} //implementation of abstract method


void makeNoise()
// signature of abstract method
{
public abstract void makeNoise();
System.out.print(“wuuwuu”);
} }}
Cont..
Points to remember !!
 Methods those cannot be abstract
 Constructor , because it uses for instance variable initializing.
 Static method, because it cannot be overridden.
 Private method, because it cannot be inherited and overridden.
 final method, because it cannot be overridden.
Encapsulation
 Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse.
 In encapsulation the variables of a class will be hidden from other classes, and
can be accessed only through the methods of their current class, therefore it is
also known as data hiding.
 To achieve encapsulation in Java
 Declare the variables and methods of a class as private.
 Provide public setter and getter methods to access and modify the
variables values.
setter and getter: setter method used to set/initialize instance variables, and getter method
used to accept the instance variable value that has been set by the setter method
Example:
if the instance variable is name setter method = setName(param), getter method =getName()
Sample code
public class customer { public class customerDemo {
private int custID; public static void main(String[] args)
public customer(int id) {
{ customer cust1=new customer(2233);
custID=id; System.out.println("Customer ID: "
Correct (we can
} +cust1.getCustID()); access by getter
method)
public int getCustID() System.out.println("Customer ID: "
{ +cust1.custID);
Wrong usage (we
return custID; } cannot use private
instance variable )
}} }

You might also like