0% found this document useful (0 votes)
2 views35 pages

Oops with java for BCA

Uploaded by

aishasharma2551
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
2 views35 pages

Oops with java for BCA

Uploaded by

aishasharma2551
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 35

Oops with java

What is Object-Oriented Programming (OOP)?


OOP is a programming paradigm based on the concept of
"objects", which are instances of classes. It enables
developers to create modular, reusable, and maintainable
code. The primary concepts in OOP are:
1. Classes and Objects
2. Encapsulation
3. Inheritance
4. Polymorphism
5. Abstraction
6. Association
7. Aggregation
8. Composition
1. Classes and Objects
Classes
A class is a blueprint for creating objects. It defines a
datatype by bundling data and methods that work on the
data into one single unit. Classes typically represent entities,
such as a Car, Person, or Animal, with attributes and
behaviors.
• Attributes (Fields/Properties): Variables that hold the
state of an object.
• Methods: Functions defined inside a class that describe
the behaviors of the object.

CODE :

public class Car {


// Fields
private String color;
private String model;
private int year;

// Constructor
public Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
}

// Method to display car details


public void displayInfo() {
System.out.println("Car Model: " + model);
System.out.println("Car Color: " + color);
System.out.println("Car Year: " + year);
}
}

Objects
Objects are instances of classes. They represent real-world
entities with a unique identity, state, and behavior.

Code:

public class Main {


public static void main(String[] args) {
Car car1 = new Car("Red", "Toyota", 2020);
car1.displayInfo();
Car car2 = new Car("Blue", "Honda", 2018);
car2.displayInfo();
}
}
In this example, car1 and car2 are objects of the Car class,
each with its own state and behavior.

2. Encapsulation
Encapsulation is the concept of wrapping data (variables) and
code (methods) together as a single unit. In encapsulation,
the variables of a class will be hidden from other classes, and
can only be accessed through the methods of their current
class. This is also known as data hiding.
Benefits:
• Protects the internal state of an object from unwanted
or harmful external modification.
• Reduces complexity by hiding the internal
implementation details.
• Improves maintainability and flexibility
CODE:

public class BankAccount {


private String accountNumber;
private double balance;

// Constructor
public BankAccount(String accountNumber, double
balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}

// Getter for account number


public String getAccountNumber() {
return accountNumber;
}

// Getter for balance


public double getBalance() {
return balance;
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
} else {
System.out.println("Deposit amount must be
positive.");
}
}

// Method to withdraw money


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
} else {
System.out.println("Invalid withdrawal amount.");
}
}
}
In the BankAccount class, the fields accountNumber and balance are
private, ensuring that they can only be accessed and modified
through the public methods provided.
3. Inheritance
Inheritance is a mechanism where a new class inherits the
properties and behaviors of an existing class. The class being
inherited from is called the superclass or parent class, and
the class that inherits is called the subclass or child class.
Benefits:
• Promotes code reuse.
• Establishes a natural hierarchy and improves code
organization.
• Allows for the extension of existing classes without
modifying them.
CODE :

// Superclass
class Vehicle {
private String brand;

public Vehicle(String brand) {


this.brand = brand;
}

public String getBrand() {


return brand;
}

public void honk() {


System.out.println("Vehicle is honking");
}
}

// Subclass
class Car extends Vehicle {
private int numberOfDoors;

public Car(String brand, int numberOfDoors) {


super(brand); // Call the constructor of the superclass
this.numberOfDoors = numberOfDoors;
}

public int getNumberOfDoors() {


return numberOfDoors;
}

public void displayCarDetails() {


System.out.println("Brand: " + getBrand());
System.out.println("Number of doors: " +
numberOfDoors);
}
}

public class Main {


public static void main(String[] args) {
Car car = new Car("Toyota", 4);
car.honk(); // Inherited method
car.displayCarDetails(); // Method of Car class
}
}

In this example, the Car class inherits properties and


methods from the Vehicle class.

4. Polymorphism
Polymorphism allows objects to be treated as instances of
their parent class rather than their actual class. There are two
types of polymorphism in Java:
• Compile-time Polymorphism (Method Overloading):
When multiple methods have the same name but
different parameters.
• Runtime Polymorphism (Method Overriding): When a
subclass provides a specific implementation of a method
already defined in its superclass.
Benefits:
• Simplifies code maintenance and readability.
• Promotes flexibility and integration.
Method Overloading (Compile-time Polymorphism):

CODE :
class MathOperations {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}

public class Main {


public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum of integers: " + math.add(5,
10));
System.out.println("Sum of doubles: " + math.add(5.5,
10.5));
}
}

Method Overriding (Runtime Polymorphism):

CODE:
class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Meow");
}
}

public class Main {


public static void main(String[] args) {
Animal myAnimal = new Cat(); // Polymorphism
myAnimal.makeSound(); // Calls the Cat's makeSound
method
}
}
In the above examples, method overloading allows different
methods to share the same name but differ in parameters,
while method overriding allows a subclass to provide a
specific implementation of a method that is already defined
in its superclass.
5. Abstraction
Abstraction is the concept of hiding the complex
implementation details and showing only the essential
features of the object. Abstraction can be achieved using
abstract classes and interfaces.
Benefits:
• Reduces complexity.
• Enhances code readability and maintainability.
Example of Abstract Class:

CODE:
abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing Circle");
}
}
class Rectangle extends Shape {
@Override
void draw() {
System.out.println("Drawing Rectangle");
}
}

public class Main {


public static void main(String[] args) {
Shape circle = new Circle();
circle.draw();

Shape rectangle = new Rectangle();


rectangle.draw();
}
}
Example of Interface:
CODE :
interface Animal {
void eat();
void makeSound();
}

class Dog implements Animal {


@Override
public void eat() {
System.out.println("Dog eats bones");
}

@Override
public void makeSound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.makeSound();
}
}
In these examples, the Shape class and Animal
interface provide abstract methods that must be
implemented by any subclass or implementing class,
thus hiding the details and exposing only the necessary
functionalities.

6. Association
Association represents a relationship between two
classes. It can be one-to-one, one-to-many, many-to-
one, or many-to-many. Association is a broader
concept that encompasses both aggregation and
composition.
Example:

CODE:
class Author {
String name;

public Author(String name) {


this.name = name;
}
}

class Book {
String title;
Author author;

public Book(String title, Author author) {


this.title = title;
this.author = author;
}

public void displayDetails() {


System.out.println("Book: " + title);
System.out.println("Author: " + author.name);
}
}

public class Main {


public static void main(String[] args) {
Author author = new Author("George Orwell");
Book book = new Book("1984", author);
book.displayDetails();
}
}
In this example, the Book class has an association with the Author class.
7. Aggregation
Aggregation is a specialized form of association where one
class represents a part of another class. It is a "has-a"
relationship but with a weaker bond than composition.

Example:
CODE:

class Engine {
String type;

public Engine(String type) {


this.type = type;
}
}

class Car {
String model;
Engine engine;

public Car(String model, Engine engine) {


this.model = model;
this.engine = engine;
}

public void displayDetails() {


System.out.println("Car Model: " + model);
System.out.println("Engine Type: " + engine.type);
}
}

public class Main {


public static void main(String[] args) {
Engine engine = new Engine("V8");
Car car = new Car("Ford Mustang", engine);
car.displayDetails();
}
}
In this example, the Car class contains an Engine object, demonstrating
aggregation.
8. Composition
Composition is a stronger form of aggregation. If the
containing object is destroyed, the contained objects are also
destroyed. This is a "part-of" relationship.
Example:
CODE:

class Heart {
public void pump() {
System.out.println("Heart is pumping blood");
}
}

class Human {
private final Heart heart;

public Human() {
this.heart = new Heart();
}

public void live() {


heart.pump();
}
}

public class Main {


public static void main(String[] args) {
Human human = new Human();
human.live();
}
}
In this example, the Human class contains a Heart object, demonstrating
composition. If the Human object is destroyed, the Heart object is also
destroyed.
=>
The four pillars of Object-Oriented Programming
(OOP) are Encapsulation, Inheritance,
Polymorphism, and Abstraction. These principles
provide a framework for building modular and
maintainable software.

1. Encapsulation
Encapsulation is the bundling of data (attributes)
and methods (functions) that operate on the data
into a single unit, typically a class. It restricts
direct access to some of the object's components,
which can help prevent accidental interference
and misuse of the data.
Key Points:
• Data Hiding: Internal state of the object is
hidden from the outside. Only the object's
methods can interact with its internal state.
• Access Modifiers: Control access to the class's
fields and methods. Common modifiers
include private, protected, and public.
Example:
CODE:
public class BankAccount {
private String accountNumber;
private double balance;

// Constructor
public BankAccount(String accountNumber, double
balance) {
this.accountNumber = accountNumber;
this.balance = balance;
}

// Getter for account number


public String getAccountNumber() {
return accountNumber;
}

// Getter for balance


public double getBalance() {
return balance;
}
// Method to deposit money
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
} else {
System.out.println("Deposit amount must be
positive.");
}
}

// Method to withdraw money


public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
} else {
System.out.println("Invalid withdrawal amount.");
}
}
}

In the BankAccount class, the fields accountNumber and balance are encapsulated and
can only be accessed or modified through the class's public methods.
2. Inheritance
Inheritance is a mechanism where one class (child or
subclass) inherits the attributes and methods of another class
(parent or superclass). This promotes code reuse and
establishes a natural hierarchical relationship between
classes.
Key Points:
• Reusability: Allows the child class to reuse the fields and
methods of the parent class.
• Extensibility: Enables the child class to extend or
override the behaviors of the parent class.
Example:
CODE:
// Superclass
class Vehicle {
private String brand;

public Vehicle(String brand) {


this.brand = brand;
}

public String getBrand() {


return brand;
}
public void honk() {
System.out.println("Vehicle is honking");
}
}

// Subclass
class Car extends Vehicle {
private int numberOfDoors;

public Car(String brand, int numberOfDoors) {


super(brand); // Call the constructor of the superclass
this.numberOfDoors = numberOfDoors;
}

public int getNumberOfDoors() {


return numberOfDoors;
}

public void displayCarDetails() {


System.out.println("Brand: " + getBrand());
System.out.println("Number of doors: " +
numberOfDoors);
}
}

public class Main {


public static void main(String[] args) {
Car car = new Car("Toyota", 4);
car.honk(); // Inherited method
car.displayCarDetails(); // Method of Car class
}
}

In this example, the Car class inherits properties and methods from the Vehicle class.

3. Polymorphism
Polymorphism allows objects to be treated as instances of
their parent class rather than their actual class. This enables a
single interface to represent different underlying forms (data
types). There are two types of polymorphism:
• Compile-time Polymorphism (Method Overloading):
Methods with the same name but different parameters.
• Runtime Polymorphism (Method Overriding): A
subclass provides a specific implementation of a method
that is already defined in its superclass.
Key Points:
• Flexibility: Different classes can be treated through the
same interface.
• Interchangeability: Objects of different classes can be
treated as objects of a common superclass.

Method Overloading (Compile-time Polymorphism):


CODE:

class MathOperations {
public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}
}

public class Main {


public static void main(String[] args) {
MathOperations math = new MathOperations();
System.out.println("Sum of integers: " + math.add(5,
10));
System.out.println("Sum of doubles: " + math.add(5.5,
10.5));
}
}

Method Overriding (Runtime Polymorphism):


CODE:
class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}

class Cat extends Animal {


@Override
public void makeSound() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal myAnimal = new Cat(); // Polymorphism
myAnimal.makeSound(); // Calls the Cat's makeSound method
}
}

In the above examples, method overloading allows different methods to share the same name but
differ in parameters, while method overriding allows a subclass to provide a specific implementation
of a method that is already defined in its superclass.

4. Abstraction
Abstraction is the concept of hiding the complex
implementation details and showing only the essential
features of the object. It is achieved using abstract classes
and interfaces.
Key Points:
• Simplification: Reduces complexity by hiding the
implementation details.
• Focus on Essentials: Allows developers to focus on what
an object does rather than how it does it.
Example of Abstract Class:
CODE:
abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing Circle");
}
}

class Rectangle extends Shape {


@Override
void draw() {
System.out.println("Drawing Rectangle");
}
}

public class Main {


public static void main(String[] args) {
Shape circle = new Circle();
circle.draw();

Shape rectangle = new Rectangle();


rectangle.draw();
}
}

Example of Interface:
CODE:

interface Animal {
void eat();
void makeSound();
}

class Dog implements Animal {


@Override
public void eat() {
System.out.println("Dog eats bones");
}

@Override
public void makeSound() {
System.out.println("Dog barks");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.makeSound();
}
}

In these examples, the Shape class and Animal interface provide abstract methods that
must be implemented by any subclass or implementing class, thus hiding the details and
exposing only the necessary functionalities.
Conclusion

Understanding the four pillars of OOP—Encapsulation, Inheritance,


Polymorphism, and Abstraction—is crucial for developing robust,
maintainable, and reusable software. These principles provide a
structured approach to programming, making it easier to manage and
extend codebases.

You might also like