0% found this document useful (0 votes)
5 views43 pages

Chapter Four

Uploaded by

nahit533
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)
5 views43 pages

Chapter Four

Uploaded by

nahit533
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

Chapter Four

OOP Concepts

Compiled By: Nigusu Y. ([email protected] )

1
8/14/2025
Inheritance
o Inheritance is one of the principles of object-oriented programming that

allows the creation of hierarchical classifications.


o Inheritance is the process by which one class object acquire or get the

properties or characteristics or functionality of another class object.


o In the language of Java, a class that is inherited is called a superclass.

o The class that does the inheriting is called a subclass

o A subclass is a specialized version of a superclass.

o A subclass inherits all of the variables and methods defined by the

superclass and adds its own, unique elements.


o Inheritance is the mechanism by which code reusability is achieved.

8/14/2025 2
Con’t
▪ A subclass is more specific than its superclass and represents a smaller, more
specialized group of objects

▪ Inheritance is a form of software reusability in which new classes are created


from existing classes by absorbing their attributes and behaviors and adding
new capabilities the new classes require

▪ Java supports inheritance by allowing one class to incorporate another class


into its declaration.

▪ Java does not support multiple inheritance (as C++ does) but it does support
the notion of interfaces.

▪ Interfaces help Java achieve many of the advantages of multiple inheritance


without the associated problems
8/14/2025 3
Inheritance Basics
▪ To inherit a class use the extends keyword.
▪ To create a superclass called A and a subclass called B.
public class A {
//….
}
public class B extends A {
//….
}
▪ The extends keyword indicates that you are making a new class that derives from
an existing class.
▪ Each subclass inherits all variables and methods from the super class except
private variables and methods.
▪ Objects that are derived from other object "resemble" their parents by inheriting
both state (fields) and behavior (methods).

8/14/2025 4
Demonstration f Inheritance
public class Calculation
{
int z;
public void addition (int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z); }
}
public class My_Calculation extends Calculation
{
public void multiplication (int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[])
{
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo. multiplication(a, b);
}
8/14/2025 5
}
Single Inheritance
o The mechanism by which subclass is derived from supper class is known as single inheritance.
o When a class extends another one class only then we call it a single inheritance.
Class Parent {
public void print()
{
System.out.println(“super class method");
}
}
Class Child extends Parent
{
public void display()
{
System.out.println(“subclass method");
}
public static void main(String args[])
{
Child ob = new Child();
ob.print(); //calling super class method
ob.display(); //calling local/subclass method
8/14/2025 6
}}
Multilevel Inheritance
o When a subclass is derived from a derived class is known as the multilevel inheritance.
o Its a mechanism in OO technology where one can inherit from a derived class, there by

making this derived class the base class for the new class.
Class Gparent
{
public void Print() {
System.out.println ("Class Print method“ ); }}
Class Parent extends Gparent
{
public void Show()
{
System.out.println ("class Show method");
}}
Class Child extends Parent
{
public void Display() {
System.out.println("class Display method");
}
public static void main(String args[])
{
Child obj = new Child();
obj. Print(); //calling grand parent class method
obj. Show(); //calling parent class method
obj. Display(); //calling local method
8/14/2025 7
}}
Multiple Inheritance
o Multiple Inheritance refers to the concept of one class extending (Or inherits)
more than one base class.

o The inheritance we learnt earlier had the concept of one base class or parent.

o The problem with multiple inheritance is that the derived class will have to manage
the dependency on two base classes.

o Multiple Inheritance is very rarely used in software projects.

o Using Multiple inheritance often leads to problems in the hierarchy.

Example: Suppose the C class inherits A and B classes. If A and B classes have same
method and you call it from child class object, there will be ambiguity to call method of
A or B class.

o In java programming, multiple and hybrid inheritance is supported through


interface only. 8/14/2025 8
//demo of multiple inheritance
class Cat extends Animal, Bird
class Animal
{ //suppose if it were
void fly()
{ {
System.out.println ("Hello"); Public Static void main(String args[])
}
} {
class Bird
Cat obj=new Cat();
{
void fly() //Now
{
which fly() method would be invoked?
System.out.println ("Welcome");
} obj.fly();
}
}

}
8/14/2025 9
Hierarchical Inheritance
o In such kind of inheritance one class is inherited by many sub classes.

o In below example class B,C and D inherits the same class A.

o A is parent class (or base class) of B,C & D.

8/14/2025 10
Examples of Hierarchal Inheritance
class Animal
{
public static void main(String[] args)
public void eat (String str) { {
System.out.println("Eating for grass"); Animal a = new Animal();
} Cat b = new Cat();
} Dog c = new Dog();
class Cat extends Animal { Goat d = new Goat();
public void eat (String str) { a.eat("grass");
System.out.println("Drinking for milk"); b.eat("milk");
}
c.eat(“meat");
}
class Dog extends Animal {
d.eat("grass");
public void eat (String str) { }
System.out.println("Eating for meat"); }
}
}
Output
class Goat extends Animal {
public void eat (String str) { Eating for grass
Drinking for milk
System.out.println(“Eating for leaf"); Eating for meat
} Eating for leaf
8/14/2025 11
Hybrid Inheritance
o Hybrid inheritance is a combination of Single and Multiple inheritance.

o A hybrid inheritance can be achieved in the java in a same way as

multiple inheritance can be using interfaces.

o By using interfaces you can have multiple as well as hybrid inheritance in Java.

8/14/2025 12
Summary of Inheritance

8/14/2025 13
Super Keyword
o A subclass can also explicitly call a constructor of its immediate superclass.

o This is done by using the super constructor call.

o A super constructor call in the constructor of a subclass will result in the

execution of relevant constructor from the superclass, based on the arguments


passed.
super(parameter-list);

o The followings are the use of super keyword:

✓Access parent class fields or methods when hidden in the child class.

✓Call parent class constructors to initialize parent class variables.

✓Invoke parent class methods that have been overridden in the child class.

8/14/2025 14
public class Arithmetic
{
double x ;
double y=20;
Arithmetic (double x, double y) { //Parameterized Constructor
this.x=x;
this.y=y;
}
}
public class Addition extends Arithmetic {
Addition(double x, double y)
{
super (x,y); // Calls the constructor of the Arithmetic class
}
}
public class Multiplication extends Arithmetic
{
double z; //Subclass-specific variable
Multiplication (double x, double y, double z)
{
super(x,y); ) // Calls the constructor of the Arithmetic class
this.z=z; // Initializes the extra variable specific to Multiplication
}
} 8/14/2025 15
The Super Keyword –To Initialize Age Variable By Constructor
class Parent
{
int age;
Parent(int age) // Constructor of the Parent class
{
this.age = age;
}
public void getAge()
{
System.out.println("The value of the variable named age in super class is: " + age); }
}
public class Child extends Parent
{
Child(int age) // Constructor of the Child class
{
super(age); // Calls the constructor of the Parent class
}
public static void main(String args[])
{
Child s = new Child(24); // Create an instance of the Child class
s.getAge(); // Call the getAge() method
}
8/14/2025 16
}
Polymorphism
o Polymorphism is the ability to create variables and methods that has more than one
form.
o In object-oriented programming, this refers to the ability of objects to have many
methods with different implementations.
o Polymorphism is the quality that allows one interface to access a general class of
actions.
o Polymorphism means one name many forms.
Example: Person behaves SON in house at the same time that person
behaves EMPLOYEE in office.

o Polymorphism – is achieved through:


▪ Method Overloading -defining methods in same class with different signatures
(parameters, type).
▪ Method Overriding -defining methods in super and subclasses with the same
signature (parameter, type). 8/14/2025 17
Method Overloading
▪ Method Overloading is defining two or more methods with the same name within the same
class.

▪ However, Java has to be able to uniquely associate the invocation of a method with its
definition relying on the number and types of arguments.

▪ Therefore, the same named methods must be distinguished:


✓ by the number of arguments
✓ by the types of arguments

▪ Overloading and inheritance are two ways to implement polymorphism.

▪ When java call an overloaded method, it simply executes the version of the method whose
parameters match the arguments.

▪ Two methods are overloaded if the:


o Number of parameters are different
o Type of parameters is different
o Order of parameters is different
8/14/2025 18
Con’t
1. Number of parameters are different
public void add(int i) { System.out.println(i+i); } //Has only one parameter
public void add(int i, int j) { System.out.println(i+j); } //Has two parameter
public void add(int i, int j, int k) { System.out.println(i+j+k); } //Has three parameter

2. Type of parameters is different

public void add(int i, int j) { System.out.println(i+j); } //Has two integer type parameters
public void add(double i, int j) { System.out.println(i+j); } //Has one int & one double type parameters

3. Order of parameters is different

public void add(double i, int j) { System.out.println(i+j); } //Order is double and int


public void add(int i, double j) { System.out.println(i+j); } //Order is int and double

8/14/2025 19
Example of Method Overloading
public class Area
{
public void computeArea (double base, double height)
{
double area = (base* height)/2;
System.out.println(“The area of Triangle is: ”+area);
}
public void computeArea (int width, int length)
{
double area = width*length;
System.out.println(“The area of Rectangle is: ”+area);
}
public void computeArea (double radius)
{
double area = Math.PI*radius* radius;
System.out.println(“The area of Circle is: ”+area);
}
public static void main(String args[])
{
Area a = new Area();
a. computeArea(7.5,5.2);
a. computeArea(7,5);
a.computeArea(10.5);
} 8/14/2025 20
}
Method Overriding
✓ In a class hierarchy, when a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the subclass is said to
override the method in the superclass.
✓ A subclass can override a method defined in its superclass by providing a new
implementation for that method
✓ When an overridden method is called from subclass object, the version in the
subclass is called not the superclass version.
✓ The return type, method name, number and type of the parameters of overridden
method in the subclass must match with the method in the superclass.
✓ You can call the superclass variable & method from the subclass with super
keyword.
super.variablename;
super.overriddenMethodName();
8/14/2025 21
o If subclass provides the specific implementation of the method that has been provided

by one of its superclass, it is known as method overriding.

o Method overriding is used to provide specific implementation of a method that is

already provided by its super class. Method overriding is used for runtime
polymorphism.

o General rules

✓ Final methods can not be overridden

✓ Static methods can not be overridden

✓ Private methods can not be overridden

✓ The overriding method must have same return type (or subtype)

✓ Abstract methods in an interface or abstract class are meant to be overridden in

derived concrete classes otherwise compile-time error will be thrown. 8/14/2025 22


//Example
@Override
public class Figure
{ public double area() //overridden method
double dim1;
double dim2; {
Figure (double a , double b)
System.out.println("Area for rectangle.");
{
dim1=a; return(dim1*dim2);
dim2=b;
} }
double area()
public static void main (String []agrs)
{
System.out.println("Area for figure."); {
return(dim1*dim2);
} Figure fig= new Figure(10.5 , 10.0);
}
Rectangle rec= new Rectangle(9.0 , 5.9);
public class Rectangle extends Figure
{ System.out.println("Area is :“ + fig.area());
Rectangle (double a, double b)
{ System.out.println("Area is :“ + rec.area());
super (a ,b);
}
}
}
8/14/2025 23
Final Keyword
o A variable declared as final becomes a constant. Once it is assigned a value, it cannot

be reassigned.

o A method declared as final cannot be overridden by any subclass.

o A class declared as final cannot be extended (i.e., no subclasses can be created).

o Example
class A {
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
8/14/2025 24
}
Encapsulation
o Encapsulation is a programming mechanism that binds together code and the data

it manipulates, and that keeps both safe from outside interference and misuse.

o Encapsulation is the concept of hiding the implementation details of a class and

allowing access to the class through a public interface.

o The ability to change the behaviour of your code without changing your

implementation code is a key benefit of encapsulation.

o It hides certain details and only show the essential features of the object.

o We can prevent accession of object's data by declaring them as private & control

access to them.

o If you declare private variables in source code, it will achieve encapsulation

because it restricts access to that particular data.


8/14/2025 25
Real world Example of Encapsulation
o Example-1: Mobile Phone and Mobile Phone Manufacturer

✓ Suppose you are a Mobile Phone Manufacturer and you designed and
developed a Mobile Phone design(class), now by using machinery you are
manufacturing a Mobile Phone(object) for selling, when you sell your Mobile
Phone the user only learn how to use the Mobile Phone but not that
how this Mobile Phone works.

o Example- 2: TV operation

✓ It is encapsulated with cover and we can operate with remote and no


need to open TV and change the channel. Here everything is in private
except remote so that anyone can access not to operate and change the
things in TV.

8/14/2025 26
public class rectangle
public int getWidth()
{
{
private int length;
return width;
private int width;
}
public rectangle(int len, int wid)
{ public int displayArea()
length=len; width=wid;
} {
public void setLength(int l)
{ System.out.println(getLength() * getWidth() ) ;
length = l; }
}
public int getLength() public static void main(String args [ ])
{
return length; {
} Rectangle b=new rectangle(3,4);
public void setWidth(int w)
{ b.displayArea();
width = w;
} }
}
8/14/2025 27
How to hide implementation details?
o Keep your class instance variables private or protected. But how could we

access these protected instance variables?

o Make instance methods public and access private or protected variables through

public methods.

o For maintainability, flexibility, and extensibility

✓ Keep instance variables protected (with an access modifier, often

private).

✓ Make public accessor methods, and force calling code to use those

methods rather than directly accessing the instance variable.

✓ For the methods, use the Java naming convention of set and get.
8/14/2025 28
o Step 1: Declare variables as private so that nobody can access them from outside.

public class Employee {


private double salary;
o Step 2: Provide public setters and getters methods for accessing the private variables.

public void setSalary(double salary) {


this.salary = salary; }
public double getSalary() { return salary; } }
o Step 3: Create an object in main method and access the public methods.

public static void main(String[] args) {


Employee emp = new Employee ();
emp.setSalary(2000); //set Salary to 2000
emp.getSalary(); //2000
}}
o The public setXXX and getXXX methods are the access points of the instance variables of

the class.
8/14/2025 29
//Demonstrating Encapsulation public String getName( )
public class Man {
{ return name;
private int age; }
private String name; public static void main ( String args [])
public void setAge(int newAge) {
{
Man m = new Man ( ) ;
age = newAge;
} m.setName( "James ") ;
public void setName(String newName) m.setAge( 20) ;
{
System.out.println( "Name : " + m.getName( ) );
name = newName;
} System.out.println( " Age : " + m. get Age( ) );
public int getAge( )
}
{
return age; }
} 8/14/2025 30
Abstraction
o Abstraction means putting all the variables and methods in a class which are

essential feature without representing the background details.

o Abstraction is a process of hiding the implementation details and showing only

functionality to the user.

o In other words, the user will have the information on what the object does instead

of how it does it.

o In Java, abstraction is achieved using Abstract classes and Interface.

o Example:

▪ Postman: He is not bothered what is inside your parcel. He's job is to read

the address and deliver. It's abstraction. It is safe isn't it? Just get a job done
by providing few details.
8/14/2025 31
Abstract Class
o An abstract class is a class that is declared abstract.
o Abstract classes are made up of one or more abstract methods.
o Abstract classes cannot be instantiated because they represent abstract concept
(Do not allow to create object of class if we define the class as abstract)
o Abstract class contain fields that are not static and final as well as

implemented methods.
o abstract method is a method that is declared without an implementation

(body).

o Example:
✓Food represents the abstract concept of things that we can eat, that is why
we have never seen the instance of food what we see instead are instances
of burger, apple, chocolate. 8/14/2025 32
Abstract Classes and Abstract Methods

33
Con’t
o Abstract classes are those that works only as the parent class or the base class and

Subclasses are derived to implement.


o Declared using abstract keyword
abstract class animal
{
}
o The body of method is provided by a subclass of the class in which the abstract
method is declared.
Syntax: abstract returnType methodName();
o Abstract class can’t be instantiated(Object can’t be created), but can be extended to
subclasses
✓An abstract class can inter mix abstract and non abstract methods.
✓Abstract class and method cannot be declared as final.
✓Abstract method cannot be declared as static and private.
8/14/2025 34
//Example of Abstract Classes
abstract class Shape
{
abstract void draw(); //abstract method
}
class Rectangle extends Shape
{
void draw()
{
System.out.println(“Drawing Rectangle”);
}
}
class Triangle extends Shape{
void draw()
{
System.out.println(“Drawing Triangle”);
}}
public static void main(String args[])
{
Shape s1=new Rectangle(); //object of Rectangle
s1.draw();
s2=new Triangle(); //object of triangle
s2.draw(); 8/14/2025 35
}
Encapsulation Vs Abstraction
Encapsulation Abstraction

Solves the problem at implementation level. Solves the problem at design level

Used for hiding the data and code in a single unit Used for hiding the unwanted data and giving
to protect form outside world. relevant data.

Hiding the internal details how the object does Focuses on what the object does instead of
something. how the object does it.

Achieved through access modifiers like public, Supported using interface and abstract class
private and protected.

It is inner layout, used in terms of It is outer layout, used in terms of design


implementation. level.
For example For example
✓ Inner implementation details of mobile phone, ✓ Outer look of mobile phone, like it has a
how keypad buttons and display screens are display screen and keypad buttons to dial a
connected each other using circuits. number.
8/14/2025 36
Java Interface
▪ An interface is a special kind of block containing method signatures (and possibly

constants) only.

▪ Interfaces define the signatures of a set of methods without the body.

▪ However, in an interface, no method can include a body.

▪ A class implements an interface, thereby inheriting the abstract methods of the

interface.

▪ Method bodies exist only for default methods and static methods.

▪ Unless the class that implements the interface is abstract, all the methods of the

interface need to be defined in the class.


8/14/2025 37
Con’t
▪ To implement an interface, a class must provide bodies (implementations) for the
methods described by the interface.

▪ Thus, two classes might implement the same interface in different ways, but each
class still supports the same set of methods.

▪ By providing the interface keyword, Java allows you to fully utilize the “one
interface, multiple methods” aspect of polymorphism.

▪ The interface keyword is used to declare an interface.

▪ Syntax:
interface interfaceName
{
// declare constant fields
// declare methods that abstract
// by default.
}
8/14/2025 38
Implementing Interfaces
o When a class implements an interface, a class as signing a contract, agreeing to

perform the specific behaviors of the interface.

o If a class does not perform all the behaviors of the interface, the class must declare

itself as abstract.

o A class uses the implements keyword to implement an interface.

o The implements keyword appears in the class declaration following the extends

portion of the declaration.

o The extends keyword is used to extend an interface, and the child interface inherits

the methods of the parent interface.

8/14/2025 39
Interface Inheritance Example
interface Geometry //implementing method of interface
{ public void circle_area(float radius)
void rectangle_area(int h, int w); {
void circle_area(float radius); float ar=3.14 * radius * radius;
} System.out.println("Area of circle="+ar);
//implementing interface }
class Area implements Geometry public static void main(String[] args)
{ {
//implementing method of interface //creating instance of derived class
public void rectangle_area(int h, int w)
Area obj=new Area();
{
obj.rectangle_area(12, 13);
int ar=height*width;
obj.circle_area(2.2);
System.out.println("Area of
rectangle="+ar); }

} }
8/14/2025 40
o In Java, multiple inheritance can be achieved using interfaces.

o A class can implement multiple interfaces, allowing it to inherit abstract methods

from multiple sources.

o If a class implements multiple interfaces, or an interface extends multiple

interfaces i.e. known as multiple inheritance.

8/14/2025 41
//Class implements multiple interfaces
interface Animal {
void sound();
}
interface Swimmer {
void swim();
}
class Dolphin implements Animal, Swimmer {
public void sound() { //override
System.out.println("Dolphin makes a clicking sound");
}
public void swim() { //override
System.out.println("Dolphin swims gracefully");
}
}
public static void main(String[] args) {
Dolphin dolphin = new Dolphin();
dolphin.sound();
dolphin.swim();
}
8/14/2025 42
}
o When implementation interfaces, we will consider the following points:

✓A class can implement more than one interface at a time.

✓A class can extend only one class, but implement many interfaces.

✓An interface can extend another interface, in a similar way as a class can

extend another class.

✓Interface cannot be declared as private, protected or transient.

✓All the interface methods are by default abstract and public.

✓Variables declared in interface are public, static and final by default.

✓ A class cannot implement two interfaces that have methods with same name

but different return type.

8/14/2025 43

You might also like