Chapter 5 - OOP Concepts
Chapter 5 - OOP Concepts
OOP Concepts
1
Outline
Encapsulation
Inheritance
Abstract classes and interfaces
Method overloading and overriding
Polymorphism
2
Introduction
3
Encapsulation
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.
12
Cont’d…
Elements to be inherited form parent class:
Attributes
Protected Members
Methods
Attributes
Public Members
Methods
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 }
16
Cont’d…
Types of Inheritance
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,
new Employee(); }
public Employee() {
class Person {
public Person() {
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.
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
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
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\
}
40
Implementing Interface
A class uses the implements keyword to implement an interface.
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
43
Cont’d…
subclass superclass
or or
extends
derived class base class
44
Abstract vs Interface
Abstract class Interface
1) Abstract class can have abstract and Interface can have only
non-abstract methods. abstract methods.
3) Abstract class can have final, non- Interface has only static and final
final, static and non-static variables. variables.
6) An abstract class can extend another An interface can extend another Java
Java class and implement multiple Java interface only.
interfaces.
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()
{…}
}
//************************
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