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

Chapter 5 - OOP Concepts

This document outlines key object-oriented programming concepts including encapsulation, inheritance, and polymorphism. It defines encapsulation as combining data and methods in a class, with private fields that can only be accessed via public getter and setter methods. Inheritance allows subclasses to inherit and extend functionality from parent superclasses. Polymorphism allows subclasses to override methods from superclasses.

Uploaded by

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

Chapter 5 - OOP Concepts

This document outlines key object-oriented programming concepts including encapsulation, inheritance, and polymorphism. It defines encapsulation as combining data and methods in a class, with private fields that can only be accessed via public getter and setter methods. Inheritance allows subclasses to inherit and extend functionality from parent superclasses. Polymorphism allows subclasses to override methods from superclasses.

Uploaded by

tarekegnworku5
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Chapter 5

OOP Concepts

1
Outline
 Encapsulation
 Inheritance
 Abstract classes and interfaces
 Method overloading and overriding
 Polymorphism

2
Introduction

 The three fundamental object oriented programming


principles are:
 Encapsulation (data hiding) and Data abstraction
 Inheritance
 Polymorphism
 Main purpose of these principles is to manage
software system complexity by improving software
quality factors.

3
Encapsulation

Encapsulation refers to the combining of fields and


methods together in a class such that the methods
operate on the data, as opposed to users of the class
accessing the fields directly. Class

It is a the technique which

2
involves making the fields in a M

M
1
class private and providing
access to the fields via public Fields/Data

methods.
M
4

3
M
4
Cont’d …
 If a field is declared private, it cannot be accessed by
anyone outside the class, thereby hiding the fields
within the class.
 For this reason, encapsulation is also referred to as
data hiding.
 Encapsulation can be described as a protective
barrier that prevents the code and data being
randomly accessed by other code defined outside the
class.
 The main benefit of encapsulation is the ability to
modify our implemented code without breaking the
code of others who use our code.

5
Cont’d …
public class EncapTest{ public void setAge( int newAge)
private String name; { age = newAge;
private String idNum; }
private int age; public void setName(String newName)
public int getAge() {
{ name = newName;
return age; }
} public void setIdNum( String newId)
public String getName() {
{ idNum = newId;
return name; }
} }
public String getIdNum()
{
return idNum;
}

6
Cont’d …
 The public methods are the access points to this class’s
fields from the outside java world.
 Normally these methods are referred as getters and
setters. Therefore any class that wants to access the
variables should access them through these getters and
setters.
public class RunEncap{
public static void main(String args[]){
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+ " Age : "+ encap.getAge());
} Out Put:
} Name : James Age : 20
7
Data Abstraction
 Classes normally hide the
details of their
implementation from their
clients. This is called
information hiding.
 The client cares about what
functionality a class offers, not
about how that functionality is
implemented. This concept is
referred to as data
abstraction.
8
Inheritance
 Object-Oriented Programming (OOP): allows you to
derive new classes from existing classes. This is called
inheritance.
 A class C1 extended from another class C2 is called a
subclass, and C2 is called a superclass.
 A superclass is also referred to as a supertype, a parent
class, or a base class and subclass as subtype, a child
class, an extended class, or derived class.

9
Cont’d…
 A subclass
 May inherit accessible data fields and methods from its
superclass (the immediate parent and all its Ancestors).
 May add new data fields and methods.
 May also override an inherited method by
providing its own version, or hide an inherited variable by
defining a variable of the same.
 Sometimes it is necessary for the subclass to modify
the implementation of a method defined in the
superclass.
 This is referred to as method overriding.
10
Cont’d…
 Inheritance plays a dual role:
 A subclass reuses the code from the superclass.
 A subclass (or a class that implements an interface) inherits the data
type of the superclass (or the interface) as its own secondary type.
 The inheritance relationship of subclasses and super
classes gives rise to a hierarchy.

Inheritance Hierarchy for Shapes


11
Cont’d…
 Elements to be inherited from parent class are
protected and public members.
 Private members of the superclass are not inherited
by the subclass and can only be indirectly accessed.
 Members that have default accessibility in the
superclass are also not inherited by subclasses in
other packages.
 These members are only accessible by their simple
names in subclasses within the same package as
the superclass.

12
Cont’d…
Elements to be inherited form parent class:
Attributes
 Protected Members
Methods

Attributes
 Public Members
Methods

 An instance method can be overridden only if it is


accessible.
 Thus a private method cannot be overridden, because it is
not accessible outside its own class.
 If a method defined in a subclass is private in its
superclass, the two methods are completely unrelated.
13
Cont’d…
Applications of inheritance
 Specialization
 The new class or object has data or behavior aspects
that are not part of the inherited class.
 Overriding
 Permit a class or object to replace the implementation of
an aspect—typically a behavior—that it has inherited
 Code re-use
 Re-use of code which already existed in another class.

14
Cont’d…
 In Java inheritance is represented by the key word extends.
Syntax
modifier class SubclassName extends SuperclassName
{ //body }
Example
public class Mammal extends Animal
{ //body }

 The inheritance relationship is transitive:


 if class x extends class y, then a class z, which extends class
x, will also inherit from class y.
public class Animal{ …}
public class Mammal extends Animal{…}
public class Reptile extends Animal{…}
public class Dog extends Mammal{…}
15
Cont’d…
 Now based on the above example, In Object Oriented
terms following are true:
 Animal is the superclass of Mammal and Reptile classes.
 Mammal and Reptile are subclasses of Animal class.
 Dog is the subclass of both Mammal and Animal classes.
 A very important fact to remember is that Java only
supports only single inheritance. This means that a class
cannot extend more than one class.
 Therefore the following is illegal:
public class Dog extends Animal, Mammal{…}

16
Cont’d…
Types of Inheritance

Multiple and Hybrid inheritance is not supported in Java through class.


17
Cont’d…
public class Student
{
protected String name;

public Student()
{ name = “”; }
public Student(String s)
{ name = s; }
public String getName()
{
return name;
}
}
Note: Object is the super class of all Java Classes.
18
Cont’d…
 The instanceof operator compares an object to a specified type.
 You can use it to test if an object is an instance of a class, an
instance of a subclass, or an instance of a class that implements
a particular interface.
public class Dog extends Mammal{
public static void main(String args[]){
Animal a = new Animal();
Mammal m = new Mammal();
Dog d = new Dog();
System.out.println(m instanceof Animal);
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
} Output: true true true
19
Super Keyword
 When extending a class you can reuse the immediate
superclass constructor and overridden superclass methods
by using the reserved word super.
 The keyword super refers to the superclass of the class in
which super appears. This keyword can be used in three
ways:
 To call a superclass method
 To call a superclass constructor
 To access a hidden data fields

20
Cont’d…
 Unlike data fields and methods, a superclass's constructors are
not inherited in the subclass.
 They can only be invoked from the subclasses' constructors,
using the keyword super.
 If the keyword super is not explicitly used, the superclass‘s
no-arg constructor is automatically invoked.
 You must use the keyword super to call the superclass
constructor.
 Invoking a superclass constructor’s name in a subclass causes a
syntax error.
 Java requires that the statement that uses the keyword super
appear first in the constructor.
21
Cont’d…
Example
class A{
public int a, b, c;
public A(int p, int q, int r)
{
a=p;
b=q;
c=r;
}
public void Show()
{
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}// end of class A
22
Cont’d…
public class B extends A{
public int d;
public B(int l, int m, int n, int p){
super(l, m, n);
d=p;
}
public void Show(){
super.Show()
System.out.println("d = " + d);
}
public static void main(String args[])
Output
{ a=4
B b1 = new B(4,3,8,7); b=3
b1.Show(); c=8
} d=7
}//end
23
of class B
Constructor Chaining
 A constructor may invoke an overloaded constructor or its
superclass’s constructor.
 If none of them is invoked explicitly, the compiler puts super()
as the first statement in the constructor. For example,

public A() { is equivalent to public A() {


} super();
}

public A(double d) { public A(double d) {


// some statements is equivalent to
super();
} // some statements
}

 Constructing an instance of a class invokes all the super


classes' constructors along the inheritance chain. This is called
Constructor Chaining.
24
class Employee extends Person {

public static void main(String[] args) {

new Employee(); }

public Employee() {

System.out.println("Employee's no-arg constructor is invoked");

class Person {

public Person() {

System.out.println(" Person's no-arg constructor is invoked");


}

Output: Person's no-arg constructor is invoked


Employee's no-arg constructor is invoked

25
Cont’d…
 You can also use super to refer to a hidden field.
 Within a class, a field that has the same name as a field in
the superclass hides the superclass's field, even if their
types are different.
 Within the subclass, the field in the superclass cannot be
referenced by its simple name. Instead, the field must
be accessed through super.
 Generally speaking, we don't recommend hiding fields as
it makes code difficult to read.

26
Final Classes and Methods
 We may want to prevent classes from being extended. In such
case , use the final modifier to indicate that a class is final and
cannot be a parent class.
 You might wish to make a method final if the method has an
implementation that should not be changed.
 All methods in a final class are implicitly final.
 A final class cannot be extended. This is done for reasons of
security and efficiency. Accordingly, many of the Java standard
library classes are final.

Example: java.lang.System, java.lang.Math and java.lang.String.


 You cannot override final methods, methods in final classes,
27
private methods or static methods.
Abstract Classes and Methods
 Abstract classes are like regular classes with data and
methods, but we cannot create instance of abstract classes
using the new operator.
 An abstract class is one that cannot be instantiated.
 Classes that can be instantiated are known as concrete
classes.
 If a class is abstract and cannot be instantiated, the class does
not have much use unless it is subclassed. This is typically
how abstract classes come about during the design phase.
 Use the abstract keyword to declare a class abstract.

28
Example
public abstract class Employee
{ private String name, address;
public Employee(String name, String address)
{
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
}
Public String getname(){
return name;}
public void mailCheck()
{
System.out.println("Within mailCheck of Employee class ");
System.out.println("Mailing a check to " + name);
}
} 29
Cont’d…
public class Salary extends Employee
{ private double salary; //Annual salary
public Salary (String name, String address, double salary)
{ super(name, address);
salary = newSalary;
}
public void mailCheck()
{
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName());
}

30
Cont’d…
 Here we cannot instantiate a new Employee, but we can
instantiate a new Salary object
 Employee is abstract; cannot be instantiated

public class AbstractDemo


{
public static void main(String [] args)
{
Salary s = new Salary(“selam", “Dilla”, 3600.00);
Employee e = new Salary("John ", “addis ababa”, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("Call mailCheck using Employee reference--");
e.mailCheck();
}31
Cont’d…
 This would produce following result:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to selam

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John

32
An Abstract Method
 The abstract keyword is also used to declare a
method as abstract.
 An abstract methods consist of a method
signature, but no method body - its signature is
followed by a semicolon, not curly braces as usual.
 Used when a class to contain a particular method
but you want the actual implementation of that
method to be determined by child classes.

33
An Abstract Method Example
 Any shape have certain states (for example: position, orientation,
line color, fill color) and behaviors (for example: moveTo, rotate,
resize, draw) in common.
 Some of these states and behaviors are the same for all graphic
objects—for example: position, fill color, and moveTo.
 Others require different implementations—for example, resize or
draw.
 This is a perfect situation for an abstract superclass.

Shape

Circle Triangle Rectangle

34
Cont’d…
 The Shape class can look something like this:
abstract class Shape {
int x, y;
String feelColor;
...
void moveTo(int newX, int newY){...}
abstract void draw();
abstract void resize();
}
 Each non-abstract subclass of Shape, such as Circle and Rectangle, must provide
implementations for the draw and resize methods:
class Circle extends Shape {
void draw(){... }
void resize(){...}
}
class Rectangle extends Shape {
void draw(){...}
void resize(){...}
} 35
Cont’d…
 Abstract classes contain mixture of non-abstract and abstract
methods.
 If a class has at least one abstract method, then the class must
be declared abstract.
 static, private, and final methods cannot be abstract, since
these types of methods cannot be overridden by a subclass.
 Similarly, a final class cannot contain any abstract methods.
 Declaring a method as abstract has two results:
 The class must also be declared abstract. If a class contains an
abstract method, the class must be abstract as well.
 When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class.
However, if it does not, the subclass must also be declared abstract.
36
Interfaces
 An interface is not a class. Writing an interface is similar to
writing a class, but they are two different concepts.
 Interfaces are similar to abstract classes but all methods
are abstract and all data fields are static final.
 Interfaces have the following properties:
 An interface is implicitly abstract.
 Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.
 Methods in an interface are implicitly public.

37
Cont’d…
 Interfaces can be inherited (i.e. you can have a sub-interface).
 A class implements an interface, thereby inheriting the abstract
methods of the interface.
 Unless the class that implements the interface is abstract, all the
methods of the interface need to be defined in the class.
 A concrete class may implement one or several interfaces, supplying
the code for all the methods. (multiple inheritance)

38
Cont’d…
 An interface is different from a class in several ways,
including:
 You cannot instantiate an interface.
 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields.
 An interface is not extended by a class; it is implemented
by a class.
 An interface can extend multiple interfaces. It is Java’s form
of multiple inheritance.
39
Declaring Interface
 The interface keyword is used to declare an
interface.
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}

public interface Animal {


public void eat();
public void travel();
}

40
Implementing Interface
 A class uses the implements keyword to implement an interface.

public class Mammal implements Animal{


public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public static void main(String args[]){
Mammal m = new Mammal();
m.eat(); Output:
m.travel(); Mammal eats
Mammal travels
}
41
}
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.
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
}

42
Cont’d…
 The Football interface has two methods, but it inherits
two from Sports; thus, a class that implements
Football needs to implement all four methods.
 Note that an interface can extend more than one
parent interface

public interface Hockey extends Sports, Event

43
Cont’d…

subclass superclass
or or
extends
derived class base class

subinterface extends superinterface

class implements interface

44
Abstract vs Interface
Abstract class Interface

1) Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods.

2) Abstract class doesn't support Interface supports multiple


multiple inheritance. inheritance.

3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.

4) The abstract keyword is used to The interface keyword is used to


declare abstract class. declare interface.

6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.

7) An abstract classcan be extended An interface class can be implemented


using keyword "extends". using keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
45
Polymorphism
 Polymorphism can also be achieved through method
overriding and method overloading.
 Overridden methods
 If a child class has the same method as declared in the
parent class
 The implementation in the subclass overrides the
implementation in the superclass.

46
Polymorphism Example
public class Shape{
public double computeArea(){ return -1; }
public double computeCircumfrence(){ return -1; }
}
public class Circle extends Shape{
private double radius;
public Circle(double r){ this.radius = r;
}
public double computeArea(){
return Math.PI*this.radius * this.radius;
}
public double computeCircumfrence(){
return 2*Math.PI*this.radius;
}
} 47
Example …
public class Rectangle extends Shape{
private double width;
private double height;
public Rectangle(double w, double h){
this.width = 0;
this.height = 0;
}
public double computeArea(){
return this.width * this.height;
}
public double computeCircum(){
return 2*(this.width *this.height);
}
} 48
Example …
public class ShapeTest{
public static void main(String args[]){
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(4.0);
shapes[1] = new Rectangle(5, 3);
shapes[2] = new Circle(1.8);
double totalArea = 0;
for(int i = 0;i<shapes.length;i++){
totalArea+=shapes[i].computeArea(); }
System.out.println(“Total area = “ +totalArea); }
}
Out Put: Total area = 60.44424265506762
 A reference variable of type Shape is used to refer objects of types of its
subclasses (Circle and rectangle)
 What is the output of the above code if you comment out computeArea()
method in Circle and Rectangle classes? Out Put: Total area = -3.0
49
Cont’d…
 It is possible to display each shape’s type as a string.
for(int i = 0;i<shapes.length;i++){
System.out.printf( “Shape %d is a %s\n", i,
shapes[ i].getClass().getName());
}
 The output is
Shape 0 is a Circle
Shape 1 is a Rectangle
Shape 2 is a Circle

50
Cont’d…
class Holiday
{
public void celebrate()
{…}
}
//************************

class Christmas extends Holiday


{
public void celebrate()
{…}
public void listenToChristmasSongs()
{…}
}
Can we do the following statements?
Holiday day;
day = new Christmas(); day.celebrate();
day.listenToChristmasSongs();
51
Method Overriding Rules
 The argument list should be exactly the same as that of the
overridden method.
 The access level cannot be more restrictive than the
overridden method's access level.
 For example: if the super class method is declared public then the overriding method in the
subclass cannot be either private or protected.
 Instance methods can be overridden only if they are
inherited by the subclass.
 Constructors cannot be overridden.
 A method declared final, static or private cannot be
overridden.

52
Cont’d…
 Method Overloading
 Overloaded methods are methods with the same name
signature but either a different number of parameters or
different types in the parameter list.
 Compiler automatically select the most appropriate method
based on the parameter supplied.
Example
public class MultiplyNumbers {
public int Multiply(int a, int b)
{
return a * b;
}
public int Multiply(int a, int b, int c)
{
return a*b*c;
53 }
54
?
quiz
1. Can we override a java main method? Justify.
2. What is the difference between abstract class and
concrete class?
3. Can abstract class be final? Justify
4. Public class A
{ String name;
Abstruct string getname();
}
is stg wrong in this code? Justify.
5. If class A extends class B, it means that class A can
inherit all data fields and methods of class B.
True/false

55

You might also like