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

Lecture 15 - OOP Concepts II

Uploaded by

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

Lecture 15 - OOP Concepts II

Uploaded by

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

CMP120130

Object Oriented
Modeling and
Development
Lecture 15
OOP Concepts II
OOP Concepts
• The four fundamental concepts of Object-Oriented Programming (OOP) are:
o Encapsulation
o Inheritance
o Abstraction
o Polymorphism
OOP Concepts
Encapsulation
• Encapsulation is one of the key features of object-oriented programming.

• Encapsulation refers to the bundling of fields and methods inside a single class.

• It prevents outer classes from accessing and changing fields and methods of a class.

• This also helps to achieve data hiding.

• In Java, encapsulation helps us to keep related fields and methods together, which makes
our code cleaner and easy to read.
Data Hiding
• Data hiding is a way of restricting the access of our data members by hiding the
implementation details.
• Encapsulation also provides a way for data hiding.
• Access modifiers can be used to achieve data hiding.
Access Modifiers
• Access modifiers are declared immediately before the type of a member variable or the
return type of a method.
• There are four access modifiers :
o default (package access)
o public
o protected
o private
Default access modifier Ex:

• There is no actual keyword for declaring


long length;
default access modifier
long getlength() {
• It is applied by default in the absence of return length;
an access modifier. }

• Specifies that only classes in the same


package (groups of related classes and
interfaces ) can have access to class’s
variables and methods

6
public access modifier
• Specifies that class variables and methods are accessible to anyone, both
inside and outside the class
• This means that public class members have global visibility and can be
accessed by any other objects.

Ex:
• public int count;
• public boolean isActive;

7
protected access modifier
• Specifies that class members are accessible only to methods in that class and
subclasses of that class.
• This means that protected class members have visibility limited to subclasses.

Ex: protected char middleinitial;


protected char getMiddleInitial() {
return middleInitial;
}

8
static Modifier
• The static modifier specifies that a variable or method is the same for all objects of a
particular class.
• When a variable is declared as being static, it is only allocated once regardless of
how many objects are instantiated. (Typically new variables are allocated for each
instance of a class)
• All instantiated objects share the same instances of the static variable.
• When you declare a method static, it is not instantiated with each object, but is part
of the entire class.
• Therefore you invoke the method by preceding it with the class name.

9
public class BankAccount {
// Static variable to keep track of the total number of accounts created
static int totalAccounts = 0;

// Instance variables
private String accountNumber; Static Variable
private double balance; Example
// Constructor
public BankAccount(String accountNumber, double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
totalAccounts++; // Incrementing the total number of accounts when a new one is created
}
}
public class Test{
// Static method to calculate the square of a number
public static int square(int num) {
return num * num;
} Static Method
Example
public static void main(String[] args) {
int num = 5;
int result = Test.square(num);
System.out.println("Square of " + num + " is: " + result);
}
}
Final modifier
• All methods and instance variables may be overridden by default.
• If you wish to declare that you want to no longer allow subclasses to override your
variables or methods, you can declare them final.

public class Shape{ final variable


// Declaration of a final variable Example
public final float PI = 3.14;

public static void main(String[] args) {


// Attempting to change the value of a final variable will result in a compilation error
PI = 200; // This line will result in an error
System.out.println("PI value: " + PI);
}
} 12
public class Shape{
// Declaring a final method
public final void display() {
System.out.println("This is the shapeclass.");
} final Method
} Example

public class Circle extends Shape{


// Attempting to override a final method will result in a compilation error
public void display() { // This line will result in an error
System.out.println("This is the circle class.");
}
}
// Declaring a final class
final public class Circle {
//Class definition
final class
} Example
OOP Concepts
Inheritance
• Inheritance is one of the key features of OOP that allows us to create a new class from an
existing class.

• The new class that is created is known as subclass (child or derived class) and the existing
class from where the child class is derived is known as superclass (parent or base class).

• The extends keyword is used to perform inheritance in Java.

• The inheritance allows subclasses to inherit all the variables and methods of their parent
classes.
IS-A relationship

• In Java, inheritance is an IS-A relationship.


• That is, we use inheritance only if there exists an IS-A relationship between two
classes.
Inheritance may take different forms:
• Single Inheritance – Only one super class
• Multiple Inheritance – Several super classes
• Hierarchichal Inheritance – One super class, many sub classes
• Multilevel Inheritance – Derived from a derived class
https://www.tutorialspoint.com/java/images/types_of_inheritance.jpghttps://www.tutorialspoint.com/java/images/types_of_inheritance.jpg
super keyword
• The super keyword in Java is used in subclasses to access superclass members
(attributes, constructors and methods).
• Uses of super keyword
o To call methods of the superclass that is overridden in the subclass.
o To access attributes (fields) of the superclass if both superclass and subclass
have attributes with the same name.
o To explicitly call superclass no-arg (default) or parameterized constructor from
the subclass constructor.
class Animal {
// overridden method
public void display(){
System.out.println("I am an animal");
}
}

class Dog extends Animal {


// overriding method
@Override super method calling
public void display(){ Example
System.out.println("I am a dog");
}

public void printMessage(){


// this calls overriding method
display();

// this calls overridden method


super.display();
}
}
class Animal {
protected String type="animal";
}

class Dog extends Animal {


super attributes
public String type="mammal";
accessing Example
public void printType() {
System.out.println("I am a " + type);
System.out.println("I am an " + super.type);
}
}
class Animal {
// default or no-arg constructor
Animal() {
System.out.println("I am an animal");
}
// parameterized constructor
Animal(String type) {
System.out.println("Type: "+type);
}
} Calling for super class
construtor Example
class Dog extends Animal {
// default constructor
Dog() {
// calling parameterized constructor of the superclass
super("Animal");
System.out.println("I am a dog");
}
}
OOP Concepts
Abstraction

•The major use of abstract classes and methods is to achieve abstraction in Java.
•Abstraction is an important concept of object-oriented programming that allows us to
hide unnecessary details and only show the needed information.
•This allows us to manage complexity by omitting or hiding details with a simpler, higher-
level idea.
Different Types of Abstraction
• Data Abstraction
Programming languages define constructs to simplify the way information is
presented to the programmer.
• Functional Abstraction
Programming languages have constructs that ‘gift wrap’ very complex and low level
instructions into instructions that are much more readable.
• Object Abstraction
OOP languages take the concept even further and abstract programming constructs
as objects.

25
Abstract Class
• The abstract class in Java cannot be instantiated (Cannot create objects of abstract
classes).
• Use the abstract keyword to declare an abstract class.
• An abstract class can have both the regular methods, abstract methods,
and constructors like the regular class.
• If a class contains an abstract method, then the class should be declared abstract.
• An abstract class often contains abstract methods with no definitions (like an interface
does).
• Unlike an interface, the abstract modifier must be applied to each abstract method.

• An abstract class typically contains non abstract methods (with bodies), further distinguishing
abstract classes from interfaces.

• A class declared as abstract does not need to contain abstract methods.

• The child of an abstract class must override the abstract methods of the parent, or it too will
be considered abstract.

• An abstract method cannot be defined as final (because it must be overridden) or static


(because it has no definition yet).
• The use of abstract classes is a design decision – it helps us establish common elements
in a class that is too general to instantiate.

public abstract class Shape


{

//code implemetation

}
Abstract Method
• A method that doesn't have its body is known as an abstract method.

• Use the same abstract keyword to create abstract methods.

• If the abstract class includes any abstract method, then all the child classes
inherited from the abstract superclass must provide the implementation of the
abstract method.
abstract class MotorBike {
abstract void brake();
}

class SportsBike extends MotorBike {


// implementation of abstract method
public void brake() {
System.out.println("SportsBike Brake");
}
}
OOP Concepts
Polymorphism
• A reference can be polymorphic, which can be defined as "having many forms".

• Polymorphic references are resolved at run time; this is called dynamic


binding.
• Careful use of polymorphic references can lead to elegant, robust software
designs.
• Polymorphism can be accomplished using inheritance or using interfaces.
• We can achieve polymorphism in Java using the following ways:

o Method Overriding

o Method Overloading

o Operator Overloading
Overriding Methods
• If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
• In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method
overriding.
• Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
• Method overriding is used for runtime polymorphism.
class Vehicle{
//defining a method
void run(){
System.out.println("Vehicle is running");
}
}
//Creating a child class Method Overriding Example
class Bike extends Vehicle{
//defining the same method as in the parent class
@Override
void run(){
System.out.println("Bike is running safely");
}
}
Note: We have used the @Override annotation to tell the compiler
that we are overriding a method. However, the annotation is not
mandatory.
Rules for Java Method Overriding

• The method must have the same name as in the parent class

• The method must have the same parameter as in the parent class.

• There must be an IS-A relationship (inheritance).


Method Overloading
• When there are multiple functions with the same name but different parameters then
these functions are said to be overloaded.
• Functions can be overloaded by changes in the number of arguments or/and a change
in the type of arguments.

void func() { ... }


void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }
class Pattern {
// method without parameter
public void display() {
for (int i = 0; i < 10; i++) {
System.out.print("*");
}
}

// method with single parameter


public void display(char symbol) {
for (int i = 0; i < 10; i++) {
System.out.print(symbol);
}
}
}
Overloading vs. Overriding
• Overloading deals with multiple methods with the same name in the same class, but
with different signatures.

• Overriding deals with two methods, one in a parent class and one in a child class, that
have the same signature.
• Overloading lets you define a similar operation in different ways for different data.

• Overriding lets you define a similar operation in different ways for different object
types.
Final Members
A way for Preventing Overriding of Members in Subclasses

• All methods and variables can be overridden by default in subclasses.

• This can be prevented by declaring them as final using the keyword “final” as a modifier.
For example:

• final int marks = 100;

• final void display();

• This ensures that functionality defined in this method cannot be altered any. Similarly, the
value of a final variable cannot be altered.
Final Classes
A way for Preventing Classes being extended
◼ We can prevent an inheritance of classes by other classes by declaring them as final classes.
◼ This is achieved in Java by using the keyword final as follows:
final class Marks
{ // members
}
final class Student extends Person
{ // members
}
◼ Any attempt to inherit these classes will cause an error.
Interfaces
◼ Interface is a conceptual entity similar to a Abstract class.

◼ Can contain only constants (final variables) and abstract method (no implementation) - Different
from Abstract classes.

◼ Use when a number of classes share a common interface.

◼ Each class should implement the interface.


Interfaces
An informal way of realising multiple inheritance

◼ An interface is basically a kind of class—it contains methods and variables, but they have to
be only abstract classes and final fields/variables.

◼ Therefore, it is the responsibility of the class that implements an interface to supply the code
for methods.

◼ A class can implement any number of interfaces, but cannot extend more than one class at a
time.

◼ Therefore, interfaces are considered as an informal way of realising multiple inheritance in


Java.
Interfaces Definition
Syntax (appears like abstract class):

interface InterfaceName {
// Constant or Final Variable Declaration
// Methods Declaration – only method body
}
Implementing Interfaces
• Interfaces are used like super-classes who properties are inherited by classes.
• This is achieved by creating a class that implements the given interface as follows:

class ClassName implements InterfaceName1, InterfaceName2, …


{
// Body of Class
}
Extending Interfaces
• Like classes, interfaces can also be extended.

• The new sub-interface will inherit all the members of the super interface in the manner
similar to classes.

• This is achieved by using the keyword extends as follows:

interface InterfaceName2 extends InterfaceName1 {


// Body of InterfaceName2
}
END

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