0% found this document useful (0 votes)
38 views38 pages

Basic Oop Concepts

dssd

Uploaded by

shiferachala778
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)
38 views38 pages

Basic Oop Concepts

dssd

Uploaded by

shiferachala778
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/ 38

Object Oriented Programming

Chapter Five

Objects Oriented
Programming Concepts

Prepared by Boki C.
C.
Outline
 Encapsulation
 Inheritance
 Method overloading and overriding
 Polymorphism
 Abstract classes and Interfaces
Introduction
 The three pillars of object-oriented programming are
encapsulation, inheritance, and polymorphism.
Encapsulation

2
 Encapsulation is the process of bundling data and operations
together in an entity called class.
 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 a variable of
class as private
 Provide public setter and getter method to modify and view
private values
Encapsulation…
 The private keyword can be used when declaring
object variables and methods to protect them from
manipulation by external program code.
 The object should then include public methods to
retrieve the values and call the methods.
 This technique encapsulates the variables and
methods within the object structure.
 It is demonstrated in the following program
(SafeInstance.java).

4
Encapsulation
public class Car { }
private String maker; class SafeInstance{ private String color; public static
void main(String[] args) { private String bodyType; Car toyota=new Car();
private String accelerate(){ toyota.setCar("toyota","Red","Couple"); String
motion="Accelerating..."; toyota.getCar();
return motion; Car BMW=new Car();
} BMW.setCar("BMW","Green","oval");
public void setCar(String brand,String paint,String style){ BMW.getCar();
maker=brand; } color=paint; }
bodyType=style; Prepared by Boki C.
} Output
public void getCar(){ toyota paint is Red
System.out.println(maker+" paint is "+color); toyota style is Couple
System.out.println(maker+" style is "+bodyType); toyota is Accelerating...
System.out.println(maker+" is "+accelerate()+"\n");
BMW paint is Green
}
BMW style is oval
BMW is Accelerating...
Inheritance
 Inheritance is one of the foundation of object-oriented
programming because it allows the creation of
hierarchical classifications.
 Using inheritance, you can create a general class that
defines characteristics common to a set of related items.
 This class can then be inherited by other, more specific
classes, each adding their own unique feature.
 In the terminology of Java, a class that is inherited is called
a superclass(parent or base class).
 The class that does inheriting is called a subclass(child or
derived class).

6
 Therefore, a subclass is a specialized version of a
superclass.
Inheritance…
 Subclass inherits all of the members defined by the
superclass and adds its own, unique elements.
 To inherit a class, you simply incorporate the
definition of one class into another class by using the
extends keyword.
 The general form of a class declaration that inherits a
superclass is shown here:
class subclass-name extends superclass-name {
// body of class
}
Example to creates a superclass called A and a subclass called B.
8
class A{ int
k=8; void
showA(){
System.out.println("parent class method");
}}
class B extends A{ Class B inherit from A void
showB(){
System.out.println("subclass method");
} Class A is :
•superclass or
public static void main(String args[]){
•parent class or
B subob=new B(); Class B is :
•base class
subob.showA(); •subclass or
•child class or
subob.showB();
•derived class
9
System.out.println(subob.k);

}}
 An object of the child class (subOb) can access the members of the parent as well as its own
class members.
 However, the parent class object can’t access the members of the child class but it can access
its own class members only.

Final Classes
 A final class that’s declared final cannot be a super class (i.e., a class cannot
extend a final class).
 All methods in a final class are implicitly final.
 The built in class String is an example of a final class.
 Consider the below example: We cannot extend a final class.

1
0
 Output:
The type ABC cannot subclass the final class XYZ
 As you have seen on the output of the above program, class ABC cannot
subclass the final class XYZ.

Super keyword
 In sub class, “super” is a keyword used to call the constructor of parent class.
 “super ( argument );” is placed on the first line of the constructor of sub class,
to call the constructor of parent class.
1
1
 Example: super is used to invoke parent class constructor
class Animal{
Animal(){
System.out.println("Animal is created");
}} This line invokes the
parent(Animal) class
class Dog extends Animal{
Dog(){ constructor
super();
System.out.println("dog is created");
Output:
}}
Animal is created
class TestSuper{
Dog is created
public static void main(String args[]){
Dog d=new Dog();
}}

1
2
A Second Use for super
 This usage has the following general form:
super.member;
 Here, member can be either a method or an instance
variable.
 This second form of super is most applicable to
situations in which member names of a subclass hide
members by the same name in the superclass.
Let’s take an example to
understand this concept:

1
3
Output:
Child class method
Parent class method

1
4
Single inheritance
 A java class may inherit directly from only one
superclass.
 This restriction is known as single inheritance.
 The below flow diagram shows that class B extends
only one class which is A.

1
5
Single Inheritance example program

Output:
Base class method
Child class method

1
6
Multilevel inheritance
 Multilevel inheritance is where one class is inherited
from a derived class, thereby making this derived class
the base class for the new class.
 As you can see in below:- flow diagram C is subclass
or child class of B and B is a child class of A.

1
7
Multilevel Inheritance example program:
class X{
public void methodX(){
System.out.println("class x method");
}}
class Y extends X{
public void methodY(){
System.out.println("Class Y method");
}}
output
class Z extends Y{ class x method
public void methodZ(){
Class Y method
System.out.println("class Z method"); class Z method
}
public static void main(String args[]){ Z obj=new
Z(); obj.methodX();//calling grand parent class
method obj.methodY();//calling parent class method
obj.methodZ();//calling local method
}}
1
8
Hierarchical inheritance
 In such kind of inheritance one class is inherited by
many sub classes.
 In below example class B and C inherits the same
class A.

1
9
Hierchichal inheritance example program:
class Fruit{ protected void
fruitInfo(){ public class InhertanceHierarchical{
System.out.println("I am a fruit"); public static void main(String args[]){
} Mango n=new Mango();
} Apple a=new Apple();
class Mango extends Fruit{ n.mangoInfo();
public void mangoInfo(){ a.appleInfo();
fruitInfo(); }
System.out.println("My name is mango"); }
} Class Mango and class Apple inherit from
class Fruit, and this two class can access the
} member fruitInfo method which is defined in
class Apple extends Fruit{ the Fruit class.
public void appleInfo(){
Output
fruitInfo();
I am a fruit
System.out.println("My name is apple");
My name is mango
}} I am a fruit
2
0
My name is apple

Multiple Inheritance
 Some programming languages allow you to derive a subclass
from several classes.
 This capability is known as multiple inheritance.
 Java, however, does not allow multiple inheritance.
 Nevertheless, multiple inheritance can be achieved through
interfaces, which will be introduced later.
 In below example class C inherits from class A and class B.

2
1
 Multilevel inheritance is not support in java through class

Polymorphism
 Polymorphism means the ability to have many forms.
Method Overloading
 Methods of the same name can be declared in the same
class, as long as they have different sets of parameters
(determined by the number, types and order of the
parameters)—this is called method overloading.

2
2
 When an overloaded method is called, the compiler
selects the appropriate method by examining the number,
types and order of the arguments in the call.
 Method overloading is commonly used to create several
methods with the same name that perform the same or
similar tasks, but on different types or different numbers
of arguments.

2
3
Declaring Overloaded Methods
 The compiler distinguishes overloaded methods by their signature - a
combination of the method’s name and the number, types and order of
its parameters.
 Method calls cannot be distinguished by return type.
 When two methods have the same signature and different return
types, the compiler issues an error message indicating that the method
is already defined in the class.
 Overloaded methods can have different return types if the methods
have different parameter lists.
Example
 Class MethodOverload (on next slide) includes two overloaded
versions of method square - one that calculates the square of an int
(and returns an int) and one that calculates the square of a double (and
returns a double).
 Although these methods have the same name and similar parameter
lists and bodies, think of them simply as different methods.
24 Prepared by Boki C. 1/1/2024
 It may help to think of the method names as “square of int” and
“square of double,” respectively.

1/23/2020

Example This line will call a


method with integer
class MethodOverload{ public static void main(String
args[]){ parameter.
System.out.println("squere of integer 7 is “+square(7));
System.out.println("square of double 7.5 is” +square(7.5));
}
public static int square(int intValue){
System.out.println("Called square with int argument: “+ intValue);
return intValue*intValue; This line will call a
} method with

25
public static double square(double doubleValue){ double parameter.
System.out.println("Called square with double
argumenent”+doubleValue);
return doubleValue*doubleValue;
}
} Output
Called square with int argument: 7 squere
of integer 7 is 49
Called square with double argumenent 7.500000 square
of double 7.5 is 56.250000

Method Overriding
 Overriding means to provide a new implementation for a method in
the subclass.
 To override a method, the method must be defined in the subclass
using the same signature and the same return type.
 Overridden methods are in different classes related by inheritance;
overloaded methods can be either in the same class or different classes
related by inheritance.
26 Prepared by Boki C. 1/1/2024
 Overridden methods have the same signature and return type;
overloaded methods have the same name but a different parameter list.
Example
 Let us use an example to show the differences between overriding and
overloading.
 In (a) below, the method p(double i) in class A overrides the same
method defined in class B.
 However, the class B has two overloaded methods: p(double i) and
p(int i).

27
Example

Overloaded method

Overriden method

28 Prepared by Boki C. 1/1/2024


Abstract class
 An abstract class cannot be used to create objects.
 An abstract class can contain abstract methods, which are implemented in concrete
subclasses.
 Abstract class works as a parent class, which will be extended by its sub class.
 The method of sub class will override the abstract method of abstract class.

 To create an abstract class you should have to use “abstract” keyword after modifier
of the class.
 “abstract int read( )” defines a abstract method.
 “class eBooks extends books { }” means a sub class “eBooks ”extends the parent
class ”books”.
29
 “int read ( ) { }” means this method in sub class overrides the abstract method in
parent class.

Example:

30
Output
Overrides the abstract method!
public class AbstractClass{
Example:- public static void main(String
package waliso; abstract class args[]){
A{ abstract int max(int A a;
x,int y); int min(int x,int y){
B b=new B(); int
return x<y?x:y;
max=b.max(100,200);
}
int min=b.min(100,200);
}
class B extends A{ System.out.println("Max="+max);
int max(int x,int y){
System.out.println("Min="+min);
return x>y?x:y;
}
}
} Output
}
Max=200
Min=100
31
Summary about abstract class
 Abstract class should not be declared final.
 Because final class can’t be inherited.
 Abstract class should not have a private constructor.
 Abstract class can contain abstract or concrete methods.
 Abstract methods do not provide implementations
 Abstract method should not be static. Because static method
can’t be overridden.
 Abstract method shouldn’t be declared final, because final
method can’t be overridden.
 A class that contains any abstract methods must be declared
as an abstract class.
 Each concrete subclass must provide implementations of
each of the super class’s abstract methods.

32
Interfaces
 Interface is a special class, which will be implemented
by a class.
 It is used to declare a special type of class that only
contains abstract or default methods, constant (static
final) fields and static interfaces.
 It can later be implemented by classes that declare the
interface with the implements keyword.
 Interface can’t be instantiated (you can’t create an
object from interface but we can declare an object).
 Interface doesn’t have any constructor.
 Interface doesn’t have instance variable.
33
Interfaces …

Output

100

34
 “interface books” defines an interface named “books”.
 To create an interface, you should have to use the keyword “interface” after
modifier.
 “int booknumber( )” defines an empty method(abstract method) “booknumber”.
 “class eBooks implements books{ }” means class “eBooks” implements “books”
interface.
 “public int booknumber( ){ }”
implements the
booknumber( ).

Example

Output:
Implement the empty
method!

35
 Interface can’t be instantiated (you can’t create an object
from interface but we can declare an object).
e.g. Books obj=new Books()// compiler error (Books is an
interface as you have seen on the above program)
 Books obj; // correct

Example:-
interface myInterface{ public void
compareNumbers(int num1,int num2);
}
class MaxNum implements myInterface{ public void
compareNumbers(int num1,int num2){
System.out.println("Two numbers are: "+num1+" & "+num2);
if(num1>=num2)
System.out.println("Maximum is :"+num1);
else
System.out.println("Maximum is:"+num2);
}}
class MinNum implements myInterface{ public void
compareNumbers(int num1,int num2){

36
System.out.println("Two numbers are :"+num1+" & "+num2);
if(num1<=num2)
System.out.println("minimum is :"+num1);
else
System.out.println("Minimum is :"+num2);
}}
class InterfaceDemo{ public static void
main(String args[]){ MaxNum
maxObject=new MaxNum();
maxObject.compareNumbers(100,200);
MinNum minObject=new MinNum();
minObject.compareNumbers(60,80);
}}

Example Description
 “interface myInterface” defines an interface named
“myInterface”.
 “void compareNumbers ( )” defines an empty method
“void compareNumbers( )”.

37
 “class MaxNum implements myInterface { }” means
class “MaxNum” implements “myInterface” interface.
 “class MinNum implements myInterface { }” means
class “MinNum” implements “myInterface” interface.
 “public void compareNumbers( ){ }” implements the
empty method compareNumbers( ) in interface.

38

You might also like