[go: up one dir, main page]

0% found this document useful (0 votes)
19 views40 pages

Oops Concepts

Uploaded by

venkat Mohan
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)
19 views40 pages

Oops Concepts

Uploaded by

venkat Mohan
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/ 40

OOPS Concepts

Placement Training –Batch 20


What is a Class?

 A class is a blueprint or template


for creating objects. It defines the
properties (variables) and
behaviors (methods) that objects
of that class will have.

 Think of a class as a blueprint for a


car. It defines that a car has
wheels, an engine, and the ability
to start or stop, but it doesn't
represent any actual car.
Example of a Class:
// Defining a class
class Car {
// Properties (variables)
String brand;
int speed;

// Behavior (method)
void start() {
System.out.println(brand + " is starting.");
}
}
What is an Object?
An object is an instance of a class. It is a
real-world entity that has a state (values of
variables) and behavior (methods).

Think of an object as an actual car made


from the blueprint. A Honda Civic or a BMW
are objects of the "Car" class.
Example of Creating Objects:
public class Main {
public static void main(String[] args) {
// Creating an object of the Car class
Car myCar = new Car();

// Assigning values to object properties


myCar.brand = "Toyota";
myCar.speed = 120;

// Calling a method on the object


myCar.start(); // Output: Toyota is starting.
}
}
Key Points
Class: A template that defines properties
and behaviors.

Object: A specific instance of a class with


unique values.

Objects are created using the new


keyword.

One class can have multiple objects.


Four Principles of OOP
Abstraction
Encapsulatio
n
Inheritance
Polymorphis
m
Abstraction
Definition:
Abstraction in Java is a concept that hides
the implementation details and only shows
the essential features to the user. It is
achieved using abstract classes and
interfaces.
Example: Car Abstraction
In real life, when we drive a car, we just use
the steering wheel, accelerator, and
brakes.
We don’t need to know how the engine
works internally.
This is abstraction—hiding the complex
details and only exposing what is
abstract class Car {
// Abstract method (to be implemented by subclasses)
abstract void start();

// Concrete method (common for all cars)


void stop() {
System.out.println("Car is stopping...");
}
}

// Subclass implementing the abstract method


class Tesla extends Car {
@Override
void start() {
System.out.println("Tesla starts with a push button!");
}
}
// Main class to test abstraction
public class Main {
public static void main(String[] args) {
Car myCar = new Tesla(); // Upcasting
myCar.start(); // Calls Tesla's
implementation
myCar.stop(); // Calls the common
method from Car class
}
}
OUTPUT
Tesla starts with a push button!
Car is stopping...
INTERFACE
Definition:
An interface in Java is a blueprint for a class that
contains only abstract methods and constants.
It is used to achieve 100% abstraction and
supports multiple inheritance.
Example: Car Interface
 In real life, different cars have different ways to
start (e.g., key start, push-button start, voice
control).
 However, all cars must have a start mechanism,
even if the implementation varies.
 This is where an interface is useful—it defines
what should be done but not how
interface Car {
void start();
}

// Tesla class implementing the Car interface


class Tesla implements Car {
public void start() {
System.out.println("Tesla starts with a push button!");
}
}

// BMW class implementing the Car interface


class BMW implements Car {
public void start() {
System.out.println("BMW starts with a key!");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Car tesla = new Tesla();
Car bmw = new BMW();
tesla.start();
bmw.start();
}
}
OUTPUT:
Tesla starts with a push button!
BMW starts with a key!
What is Encapsulation?
Encapsulation is hiding the internal
details of a class and only allowing
controlled access to its data. It is achieved
by:
Declaring variables as private (so they
can't be accessed directly from outside the
class).
Providing public getter and setter
methods to access and update the private
data.
Think of a capsule (medicine). The
medicine inside is protected, and you can
only take it in a controlled way.
Why Use Encapsulation?

Protects data from accidental modification.

Increases security and flexibility.

Makes the code easier to maintain.


Example of Encapsulation
class BankAccount {
private double balance; // Private balance
public class Main {
variable public static void main(String[]
args) {
public BankAccount(double initialBalance) { BankAccount account = new
balance = (initialBalance > 0) ? BankAccount(1000);
initialBalance : 0; // Initialize with a valid
balance account.deposit(500);
} account.withdraw(300);
System.out.println("Balance: $"
public void deposit(double amount) { + account.getBalance()); // Output:
if (amount > 0) balance += amount; Balance: $1200
} }
}
public void withdraw(double amount) {
if (amount > 0 && amount <= balance)
balance -= amount;
}

public double getBalance() { return


balance; } // Getter for balance
}
Inheritance

Inheritance is an important pillar of OOP


(Object Oriented Programming). It is the
mechanism in Java by which one class is
allowed to inherit the features (fields and
methods) of another class.
We are achieving inheritance by
using extends keyword.
Inheritance is also known as “is-a”
relationship.

TERMINOLOGIES
1. Superclass
Java Inheritance Types

Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Multiple Inheritance
Hybrid Inheritance
Single Inheritance
class Father {
void show() { System.out.println("I am the Father."); }
}

class Son extends Father {


void display() { System.out.println("I am the Son."); }
}

public class Main {


public static void main(String[] args) {
Son obj = new Son();
obj.show();
obj.display();
}
}
OUTPUT
I am the Father.
I am the Son.
Multilevel Inheritance

class Grandfather {
void greet() { System.out.println("I am the Grandfather."); }
}

class Father extends Grandfather {


void show() { System.out.println("I am the Father."); }
}

class Son extends Father {


void display() { System.out.println("I am the Son."); }
}

public class Main {


public static void main(String[] args) {
Son obj = new Son();
obj.greet();
obj.show();
obj.display();
}
}
OUTPUT
I am the Grandfather.
I am the Father.
I am the Son.
Hierarchical Inheritance

class Father {
void show() { System.out.println("I am the Father."); }
}

class Son extends Father {


void displaySon() { System.out.println("I am the Son."); }
}

class Daughter extends Father {


void displayDaughter() { System.out.println("I am the Daughter."); }
}

public class Main {


public static void main(String[] args) {
Son obj1 = new Son();
Daughter obj2 = new Daughter();
obj1.show();
obj1.displaySon();
obj2.show();
obj2.displayDaughter();
}
}
OUTPUT
I am the Father.
I am the Son.
I am the Father.
I am the Daughter.
Polymorphism
Polymorphism means “many forms”—the
ability of an object to take multiple forms.

In Java, polymorphism allows a single


method or class to behave differently
based on the object that is calling it.
Types of Polymorphism in Java
Method Overloading (Compile-time
Polymorphism)
Method Overriding (Runtime
Polymorphism)
Method Overloading (Compile-time
Polymorphism)
 Same method name but different parameters (number or
type of parameters).
 Decided
class at compile-time
Payment { (before the program runs).
// Overloaded method for credit card payment
void pay(String cardNumber, double amount) {
System.out.println("Paid $" + amount + " using Credit
Card: " + cardNumber);
}

// Overloaded method for UPI payment


void pay(String upiID) {
System.out.println("Paid using UPI ID: " + upiID);
}

// Overloaded method for cash payment


void pay(double amount) {
System.out.println("Paid $" + amount + " in cash.");
}
}
public class Main {
public static void main(String[] args) {
Payment payment = new Payment();
payment.pay("1234-5678-9012-3456", 500); // Credit
Card Payment
payment.pay("user@upi"); // UPI Payment
payment.pay(200); // Cash Payment
}
}
Method Overriding (Runtime
Polymorphism)
 Same method name and same parameters, but different
behavior in subclasses.
 Decided at runtime (when the program runs).
// Parent class
class Vehicle {
void fuelType() {
System.out.println("Vehicles use different types of fuel.");
}
}

// Child class 1 - Car


class Car extends Vehicle {
@Override
void fuelType() {
System.out.println("Car runs on Petrol or Diesel.");
}
}
// Child class 2 - ElectricCar
class ElectricCar extends Vehicle {
@Override
void fuelType() {
System.out.println("Electric Car runs on Battery.");
}
}

public class Main {


public static void main(String[] args) {
Vehicle myVehicle1 = new Car();
myVehicle1.fuelType(); // Output: Car runs on Petrol or Diesel.

Vehicle myVehicle2 = new ElectricCar();


myVehicle2.fuelType(); // Output: Electric Car runs on Battery.
}
}
How to approach a
problem?
Problems
Create a
class MessagePrinter with a
method printMessage(String
name) which prints the
message "hello <name>".
Problem 2
Create a class Calculator with the following
methods:
calculateSum(int number1, int number2) to
calculate the sum of two numbers.
calculateSum(int number1, int number2,int
number2) to calculate the sum of two
numbers.
calculateDifference(int number1, int
number2) to calculate the difference
between two numbers.
Problem 3
Create a class Employee with
overloaded constructors to initialize
employee details based on different
combinations of arguments. Ensure
the constructors support the
creation of objects in various ways.
Company Problems
Given an array arr of integers and two integers n and k, where n is
the length of the array arr, and k is an index in the array, calculate
the difference between the sum of the numbers to the left of
index k and the sum of the numbers to the right of index k.
Input Format
The first line contains an integer n (1 ≤ n ≤ 10^5), representing
the number of elements in the array arr. The second line contains
n integers separated by spaces, representing the elements of the
array arr (-10^9 ≤ arr[i] ≤ 10^9). The third line contains an
integer k (0 ≤ k < n), representing the index in the array arr.
Constraints
1 ≤ n ≤ 10^5 -10^9 ≤ arr[i] ≤ 10^9 0 ≤ k < n
Output Format
A single integer representing the absolute difference between the
sum of the elements to the left of k and the sum of the elements
to the right of k.
Sample Input 0
5
12345
2
Sample Output 0
6
Explanation 0
The left part is [1, 2] and the right part is [4, 5]. The sums are 3 and
9, respectively. The difference is 6.
Sample Input 1
4
10 20 30 40
1
Sample Output 1
60
Problem 2
Given an array of integers arr of length n, find the
difference between the sum of elements at odd
indices and the XOR of elements at even indices.
Input Format
The first line contains an integer n, the size of the
array. The second line contains n space-separated
integers representing the elements of the array arr.
Constraints
Output Format
Print a single integer, the result of the difference
between the sum of elements at odd indices and
the XOR of elements at even indices.
Sample Input 0
4
1234
Sample Output 0
4
Sample Input 1
5
58769
Sample Output 1
3
THANK YOU

You might also like