Name: Nikku Kumar Das
University Roll Number : 10900121150
Stream : CSE 3rd year 5rd semester
Subject Code : PCC-CS503
Topic : Object-Oriented Programming (OOP)
in Java
Object-Oriented
Importance of OOP in Software
Programming
Development:
Modularity and Reusability: Breaking code into self-contained
(OOP) in Java
components for efficient reuse across the application.
•Object-Oriented Programming (OOP)
Abstraction and Clarity: Representing complex real-world concepts centers on "objects," which are instances
of classes mirroring real-world entities.
with simplified models, enhancing code readability.
•OOP employs classes, objects,
inheritance, encapsulation, and
Maintainability and Scalability: Designing code that is easy to polymorphism for system design and
update, fix, and expand as the software evolves. management.
•OOP models complex systems, enhancing
Flexibility and Adaptability: Allowing the software to accommodate code reusability and maintainability.
changes and new features without major structural modifications. •It offers a way to intuitively represent the
problem domain in software design.
Collaboration: Enabling multiple developers to work cohesively by
adhering to a common programming model.
Code Organization: Structuring code logically and hierarchically to
enhance maintainability and navigation.
Core Principles of
OOP
•Encapsulation: Encapsulation bundles data and
methods into classes, safeguarding data integrity and
allowing controlled access while shielding inner
workings from external interference.
•Inheritance: Inheritance creates hierarchies of
classes, enabling subclasses to inherit attributes and
methods from superclasses, promoting code sharing
and specialized extension.
•Polymorphism: Polymorphism permits objects of
different classes to be treated as instances of a
common superclass, facilitating flexible and
interchangeable usage, especially in method calls.
•Abstraction: Abstraction simplifies complex concepts
by defining clear interfaces while concealing intricate
implementation details, aiding in conceptualization
and maintaining a focused perspective.
Classes and Objects
Classes: Classes are blueprint templates that define Objects: Objects are instances of classes, representing
the structure and behavior of objects. They real-world entities or concepts. They are created using
encapsulate data (attributes) and methods (functions) the new keyword and can access the attributes and
that operate on that data. Classes act as user-defined methods defined in their class. Each object has its own
data types, providing a way to create multiple state (attribute values) and can interact with other
instances of similar objects. For example:
objects. For example:
class Car {
public class Main {
String brand;
public static void main(String[] args) {
int year;
Car myCar = new Car();
void startEngine() {
myCar.brand = "Toyota";
// code to start the engine
myCar.year = 2022;
}
myCar.startEngine();
void stopEngine() {
myCar.stopEngine();
// code to stop the engine
}
}
}
}
Constructors and Destructors
Constructor Destructors
Constructors are special methods within a class that are used to
Unlike some other programming languages, Java does
initialize the newly created objects.
not have explicit destructors.
They have the same name as the class and do not have a return type.
Constructors are automatically called when an object is created using Java uses a garbage collector to automatically reclaim
the new keyword. memory used by objects that are no longer reachable.
They can initialize object attributes and perform any necessary setup When an object is no longer referenced, the garbage
tasks. collector eventually deallocates its memory.
Java provides a default constructor if no constructor is explicitly
defined.
class Person {
In Java, the focus is on memory
String name;
management through automatic
Person(String n) { // Constructor
garbage collection rather than
explicit destruction. Therefore,
name = n;
constructors are widely used to
System.out.println("Person object created with name: " + name);
initialize objects.
}
}
Inheritance
Code Reuse: Inheritance allows a new class (subclass) to inherit attributes and methods from an existing class
(superclass), promoting efficient code reuse.
Hierarchy: Inheritance establishes a hierarchical relationship between classes, forming a parent-child structure
where the subclass is a specialized version of the superclass. "is-a"
Relationship: Inheritance represents an "is-a" relationship, implying that a subclass is a specific type of the
superclass. For example, a "Car" is a type of "Vehicle."
Method Overriding: Subclasses can provide their own implementation for methods inherited from the superclass,
allowing customization of behavior while maintaining the same method signature.
Access to Members: Subclasses inherit public and protected attributes and methods from the superclass. Private
members are not directly accessible in the subclass.
Superclass Constructor: Subclass constructors often call the constructor of their superclass using the super()
keyword, ensuring proper initialization of inherited attributes.
Polymorphism allows objects of different classes to be treated as objects
of a common superclass, promoting flexibility and code reuse.
Method Overriding: Subclasses can provide specific implementations for
methods declared in their superclass, allowing different classes to have
different behaviors for the same method name.
Dynamic Method Dispatch: During runtime, Java determines which method
Polymorphis to call based on the actual object type, enabling runtime polymorphism.
Example:
m class Shape {
void draw() {
System.out.println("Drawing a shape");
}
}class Circle extends Shape {
@Override
void draw() {
System.out.println("Drawing a circle");
}
}class Main {
public static void main(String[] args) {
Shape shape1 = new Circle();
shape1.draw(); // Calls Circle's draw method
}
}
Interfaces
interface Printable {
void print();
Interfaces define a contract for classes, specifying a }class Document implements Printable {
set of methods that implementing classes must @Override
provide. They enable multiple inheritance of public void print() {
behavior. System.out.println("Printing a document");
}
Example : }class Photo implements Printable {
Declaration: Interfaces are declared using the @Override
interface keyword, and classes implement an public void print() {
interface using the implements keyword. Multiple System.out.println("Printing a photo");
}
Interface
}class Main {
Implementation: A class can implement multiple public static void main(String[] args) {
interfaces, allowing it to inherit behavior from Printable doc = new Document();
multiple sources. Printable pic = new Photo();
doc.print(); // Prints "Printing a document"
pic.print(); // Prints "Printing a photo"
}
}
Encapsulation and Access Modifiers
Encapsulation: Access Modifiers:
Encapsulation is the practice of bundling data Public: Members declared as public are accessible
(attributes) and methods (functions) that operate from any class or package. They have the widest
on the data into a single unit (class), protecting the scope.
internal state and exposing controlled access Private: Members declared as private are only
points. accessible within the same class. They are used
Data Hiding: Encapsulation hides the details of for data hiding and encapsulation.
the object's internal implementation, preventing Protected: Members declared as protected are
direct access to data from outside the class.
accessible within the same class, subclass, and
Access Control: Encapsulation allows classes to package. They allow limited exposure.
define access levels for their members,
Default (Package-Private): Members with no
determining which parts of the class are
access modifier (default) are accessible within the
accessible from outside and which are not.
same package. They restrict access to a package.
Abstraction
Java Abstract classes and Java Abstract methods
Data Abstraction may also be An abstract class is a class that is declared with an abstract keyword.
defined as the process of An abstract method is a method that is declared without implementation.
identifying only the required An abstract class may or may not have all abstract methods. Some of
characteristics of an object them can be concrete methods
ignoring the irrelevant details.
A method-defined abstract must always be redefined in the subclass,
The properties and behaviors
thus making overriding compulsory or making the subclass itself
of an object differentiate it abstract.
from other objects of similar
Any class that contains one or more abstract methods must also be
type and also help in declared with an abstract keyword.
classifying/grouping the
There can be no object of an abstract class. That is, an abstract class can
objects.
not be directly instantiated with the new operator.
An abstract class can have parameterized constructors and the default
constructor is always present in an abstract class.
Wrapper classes
Wrapper classes in Java are a set of classes that allow primitive data types
to be treated as objects. They provide a way to wrap or encapsulate
primitive values in an object, enabling them to be used in situations where
objects are required. Wrapper classes are part of the Java API and are used
to bridge the gap between the object-oriented and primitive worlds.
Commonly used wrapper classes for primitive data types in Java:
Integer Wrapper Class Character Wrapper Class Double Wrapper Class
Boolean Wrapper Class
(java.lang.Integer): Wraps (java.lang.Character): (java.lang.Double): Wraps a
(java.lang.Boolean): Wraps
an int primitive type, Wraps a char primitive type, double primitive type,
a boolean primitive type,
providing methods for offering methods for providing methods for
enabling boolean value
conversions and arithmetic character-related double-precision floating-
manipulation.
operations. operations. point operations.
Float Wrapper Class
Long Wrapper Class Short Wrapper Class Byte Wrapper Class
(java.lang.Float): Wraps a
(java.lang.Long): Wraps a (java.lang.Short): Wraps a (java.lang.Byte): Wraps a
float primitive type, offering
long primitive type, short primitive type, byte primitive type,
methods for single-
providing methods for long offering methods for short providing methods for byte
precision floating-point
integer operations. integer operations. operations.
operations.