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

Chapter 2.2(OOP Principles) Lecture Iterface (1)

The document outlines the three core principles of object-oriented programming: encapsulation, inheritance, and polymorphism. It explains encapsulation as data hiding through private fields and public methods, inheritance as the ability to create new classes from existing ones, and polymorphism as the capability of objects to take on multiple forms. Additionally, it covers abstract classes and interfaces, highlighting their differences and uses in managing software complexity.

Uploaded by

Woldeab Bisrat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Chapter 2.2(OOP Principles) Lecture Iterface (1)

The document outlines the three core principles of object-oriented programming: encapsulation, inheritance, and polymorphism. It explains encapsulation as data hiding through private fields and public methods, inheritance as the ability to create new classes from existing ones, and polymorphism as the capability of objects to take on multiple forms. Additionally, it covers abstract classes and interfaces, highlighting their differences and uses in managing software complexity.

Uploaded by

Woldeab Bisrat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

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
Encapsulation
Encapsulation refers to
..
the combining of fields
and methods together in a
class such that the

M
M Class

2
1
methods operate on the
data, Fields/Data
=>It is a the technique
which involves making the 4
M
fields in a class private and

M3
providing access to the
fields via public methods.
Encapsulation
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.
Encapsulation Example
public class EncapTest{ public void setAge( int
private String newAge){
name; age = newAge;
private String }
idNum; public void setName(String
private int age; newName){
public int getAge() name = newName;
{ }
return age; public void setIdNum( String
} newId){
public String idNum = newId;
getName(){ }
return name; }
}
public String
Encapsulation, example
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.
Thepublic
variables of the EncapTest class can be
class RunEncap{
Out Put:
accessed as below:
public static void main(String args[]){
Name : James Age : 20
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName()+ " Age
: "+ encap.getAge());
}
}
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.
Inheritance
Object-oriented programming (OOP):
allows you to derive new classes from
existing classes. This is called inheritance.

In other words, Inheritance is a way to


form new classes using classes that have
already been defined.

A class C1 extended from another class C2


is called a subclass, and C2 is called a
superclass. A superclass is also refered to
as a supertype, a parent class, or a base
Inheritance
A subclass
 may inherit accessible data fields and
methods from its superclass.
 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.
Inheritance
Inheritance is employed to help reuse
existing code with little or no modification.

The inheritance relationship of subclasses


and superclasses gives rise to a hierarchy.

With the use of inheritance the information


is made manageable in a hierarchical order.
Inheritance

Inheritance Hierarchy for


Shapes
Inheritance…
Elements to be inherited form 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.
Inheritance…

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.
Inheritance…
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.
Inheritance…

In Java inheritance is represented by the

key word extends.


Syntax
modifier class SubclassName extends SuperclassName
{
//body
}

Example
public class Mammal extends Animal
{
//body
}
Inheritance…
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 Class


Inheritance…

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.
Inheritance…
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);
}
}

This would produce


following result:
true
true
Inheritance Example

class Animal {
public int numberOfLegs;
public void talk() {
System.out.println("Hello");
}
}
Inheritance Example…
class Dog extends Animal {
public int numberOfFleas;
public Dog() {
numberOfLegs = 4;
numberOfFleas = 10;
}
public void bark() {
System.out.println("Woof woof");
}
public void scratch() {
if (numberOfFleas > 0) numberOfFleas--;
}
}
Inheritance Example…
Dog d=new Dog();
d.bark();
d.scratch();
System.out.println(d.numberOfFleas);

Because the Dog class inherits from the


Animal class, we can also use the d
reference to access the methods and
properties of the Animal class. Use the
code below.

d.talk();
Super keyword
When extending a class you can reuse
the immediate superclass constructor.

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
Super keyword…

 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.
Super keyword

 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.
Super keyword
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);


}
Example…
public class B extends A{
public int d;
public B(int l, int m, int n, int p){ Output
super(l, m, n); a=
d=p; 4
} b=
public void Show(){ 3
super.show() c=
System.out.println("d = " + d);
8
}
d=
public static void main(String args[]){
7
B b = new B(4,3,8,7);
b.Show();
}
}//end of class B
Super keyword….
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.
Super keyword….

 You cannot override final methods,


methods in final classes, private methods
or static methods
Writing 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.

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
Writing Final Classes and Methods…
A final method cannot be overriden by
subclasses. This is used to prevent
unexpected behavior from a subclass
altering a method that may be crucial to
the function or consistency of the 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


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.
Abstract classes and methods
Use the abstract keyword to declare a
class abstract. The keyword appears in the
class declaration somewhere before the
class keyword.
Abstract classes and Methods
Abstract classes contain mixture of non-
abstract and 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.
The abstract keyword is also used to
declare a method as abstract.
Abstract classes and Methods
An abstract methods consist of a method
signature, but no method body - its
signature is followed by a semicolon, not
curly braces as usual.
 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.
Abstract classes and 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
Interfaces

Interfaces are similar to abstract classes


but all methods are abstract and all data
fields are static final.

An interface is not a class. Writing an


interface is similar to writing a class, but
they are two different concepts. A class
describes the attributes and behaviors of
an object.
An interface contains behaviors that a
Interfaces

Interfaces have the following properties:

An interface is implicitly abstract. You do


not need to use the abstract keyword
when declaring an interface.
Each method in an interface is also
implicitly abstract, so the abstract
keyword is not needed.
Methods in an interface are implicitly
public.
Interfaces…
Interfaces can be inherited
A class implements an 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.
Interfaces…
An interface is similar to a class in the
following ways:
 An interface can contain any number of
methods.
 An interface is written in a file with
a .java extension,
 The bytecode of an interface appears in
a .class file.
Interfaces…
However, 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.
Declaring Interfaces
The interface keyword is used to declare an
interface.

public interface NameOfInterface


{
//Any number of final, static fields
//Any number of abstract method
declarations\
}
Implementing Interfaces
A class uses the implements keyword to
implement an interface.
The implements keyword appears in the
class declaration following the extends
portion of the declaration.

interface Animal {
public void eat();
public void travel();
}
Implementing Interfaces
public class Mammal implements Animal{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels"); }
public int noOfLegs(){
return 0; }
public static void main(String args[]){
Output:
Mammal m = new Mammal(); Mammal eats
m.eat(); Mammal travels
m.travel();
}
}
Abstract vs Interface
Unlike interfaces, abstract classes can
contain fields that are not static and final,
and they can contain implemented
methods.

If an abstract class contains only abstract


method declarations, it should be
declared as an interface instead.

Multiple interfaces can be implemented


by classes anywhere in the class
Polymorphism
Polymorphism (from the Greek, meaning
“many forms”) is the ability of an object to
take on many forms.
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; }
}
Polymorphism 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);}
}
public class ShapeTest{
public static void main(String args[]){
Shape[] shapes = new Shape[3];
shapes[0] = new Circle(4.0);
Polymorphism example
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
Polymorphism…
Polymorphism can also be achieved through
method overriding and method
overloading.
Overridden methods
 Are methods that are redefined within an
inherited or subclass. They have the same
signature and the subclass definition is
used.
In other words an instance method in a
subclass with the same signature (name,
plus the number and the type of its
parameters) and return type as an instance
method in the superclass overrides the
Method overriding Rules
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 super class.
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 sub
class cannot be either private or protected.
However the access level can be less
restrictive than the overridden method's
access level.
Polymorphism…
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) {
eturn a*b*c;
}
}
Package
A Package (named collections of classes) can be
defined as a grouping of related types(classes
and interfaces) providing access protection
Packages are used in Java in-order to prevent
naming conflicts, to control access, to make
searching/locating and usage of classes,
interfaces,e.t.c.
Java has numerous built in packages: java.io,
java.lang, java.util …
Programmers can define their own packages to
bundle group of classes/interfaces etc.
Creating a package
When creating a package, put a package
statement with that name at the top of every
source file that contains the classes and
interfaces
The package statement should be the first line
in the source file.
There can be only one package statement in
each source file, and it applies to all types in the
file.
It is common practice to use lowercased names
of packages to avoid any conflicts with the
names of classes, interfaces.
If a package statement is not used then , class
Creating a package…
If a class wants to use another class in the
same package, the package name does not
need to be used.
Classes in the same package find each
other without any special syntax.
A class file can contain any number of
import statements.
The import statements must appear after
the package statement and before the
class declaration.
Let us look at an example that creates a
package called animals.
Creating a package…Example
package animals;
interface Animal {
public void eat();
public void travel();
}
//-------------------------------------------------------------------
-------
package animals;
public class MammalInt implements Animal{
public void eat()
{ System.out.println("Mammal eats"); }
public void travel()

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