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

Advance OOP With JAVA.

Advance opp

Uploaded by

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

Advance OOP With JAVA.

Advance opp

Uploaded by

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

Advance OOP with JAVA

Classes and Object


Classes
A class in Java is a blueprint or template for creating objects. It defines the
properties (attributes) and behaviors (methods) that the objects created
from the class will have. A class encapsulates data for the object and
methods to manipulate that data.
Components of a Class
 Fields (Attributes/Properties): These are variables that hold the
data for an object.
 Methods: These are functions defined inside the class that describe
the behaviors of the objects.
 Constructors: Special methods used to initialize objects.
Example

Object
An object is an instance of a class. When a class is defined, no memory is
allocated until an object of that class is created. Objects are created using
the new keyword.
Example

In this example:
 Dog is a simple class with one field (name) and one method (bark).
 In the Main class, we create an instance of the Dog class called
myDog.
 We set the name field of myDog to "Buddy" and call the bark method
on myDog, which prints "Woof!" to the console.

Pillars of OOP in JAva


Inheritance in Java

Inheritance in Java is a mechanism where a new class (called the subclass or


derived class) is created from an existing class (called the superclass or base
class).
The subclass inherits the properties and behaviors (methods and variables)
of the superclass, allowing code reuse and facilitating the creation of more
specialized classes.

We group the "inheritance concept" into two categories:

 subclass (child) - the class that inherits from another class


 superclass (parent) - the class being inherited from
 We have a superclass Animal with a method sound().
 We have a subclass Dog that extends the Animal class.
 The subclass Dog inherits the sound() method from the superclass
Animal.
 The subclass Dog also has its own method bark().
 In the Main class, we create an object of the Dog class and call both
inherited and subclass-specific methods.

Polymorphism in JAVA?
Polymorphism means "many forms", and it occurs when we have many classes
that are related to each other by inheritance.

Inheritance lets us inherit attributes and methods from another class.


Polymorphism uses those methods to perform different tasks. This allows us to
perform a single action in different ways.

For example, think of a superclass called Animal that has a method


called makeSound(). Subclasses of Animals could be Cats, Dogs - And they also
have their own implementation of an animal sound.
Encapsulation in Java?

The meaning of Encapsulation, is to make sure that "sensitive" data is


hidden from users. To achieve this:

 declare class variables/attributes as private


 provide public get and set methods to access and update the value of
a private variable
In this example:
 We have a class MyClass with a private encapsulated variable number.
 Public methods setNumber() and getNumber() are provided to set and
get the value of the encapsulated variable, respectively.
 Encapsulation ensures that the variable number is accessed and
modified only through the provided methods, maintaining data
integrity and control over its usage.

Abstraction in JAVA?

Data abstraction is the process of hiding certain details and showing only
essential information to the user.

The abstract keyword is a non-access modifier, used for classes and methods:
 Abstract class: is a restricted class that cannot be used to create objects
(to access it, it must be inherited from another class).

 Abstract method: can only be used in an abstract class, and it does not
have a body. The body is provided by the subclass (inherited from).

In this example:
 We have an abstract class Animal with an abstract method
makeSound().
 We have a concrete class Dog that extends the Animal class and
provides an implementation for the makeSound() method.
 In the Main class, we create an object of the Dog class but store it in a
reference of type Animal.
 We call the makeSound() method on the Animal reference without
knowing the specific implementation of the Dog class. This
demonstrates abstraction, where we focus on the behavior of an object
(i.e., making a sound) rather than the details of how it is implemented.
Access Modifiers
In Java, access modifiers are keywords used in object-oriented programming
to set the access level for classes, variables, methods, and constructors.
They are the primary means of enforcing encapsulation, a fundamental
concept of OOP that restricts direct access to some of the object’s
components.
This not only helps safeguard the object's internal state but also improves
maintainability and reduces the risk of errors in code.

1. private
The private access modifier is the most restrictive level of access control.
When a member (be it a field, method, or constructor) is declared private, it
can only be accessed within the same class.
No other class, including subclasses in the same package or different
packages, can access the member.
This modifier is typically used for sensitive data that should be hidden from
external classes.
Example:
public class Person {

private String name;

private String getName() {

return this.name;

In this example, the name attribute and the getName() method are only
accessible within the Person class.

2. default (no modifier)


When no access modifier is specified, Java uses a default access level, often
called package-private.
This means the member is accessible only within classes in the same
package.
It is less restrictive than private but more restrictive than protected and
public.
Example:
class Log {

void display() {

System.out.println("Displaying log information");

In this example, the Log class and its method display() are accessible only
within classes defined in the same package.

3. protected
The protected access modifier is less restrictive than private and default.
Members declared as protected can be accessed within the same package or
in subclasses in different packages.
This is particularly useful in cases where you want to hide a member from
the world but still make it available to child classes.
Example:
public class Animal {

protected String type;

protected void displayType() {

System.out.println("Type: " + type);

}
}

Here, the type attribute and the displayType() method can be accessed
within all classes in the same package and in any subclass of Animal, even if
those subclasses are in different packages.

4. public
The public access modifier is the least restrictive and specifies that the
member can be accessed from any other class anywhere, whether within or
in a different package.
This access level is typically used for methods and variables that must be
available consistently to all other classes.
Example:
public class Calculator {

public int add(int num1, int num2) {

return num1 + num2;

In this example, the add() method of the Calculator class can be accessed by
any other class.

String And String Buffer


String
The String class represents an immutable sequence of characters. Once a
String object is created, it cannot be changed.
Any modification to a String object results in the creation of a new String
object.
Declaring and Initializing a String
A String in Java can be declared and initialized in several ways:
1. Using String Literals:

2. Using the new Keyword:

3. Using Character Arrays:


StringBuffer:
A thread-safe, mutable sequence of characters. A string buffer is like a String
, but can be modified.
At any point in time it contains some particular sequence of characters, but
the length and content of the sequence can be changed through certain
method calls.
Note: Java StringBuffer class is thread-safe i.e. multiple threads cannot access it
simultaneously. So it is safe and will result in an order. A String that can be modified or
changed is known as mutable String. StringBuffer and StringBuilder classes are used for
creating mutable strings.
Declaring and Initializing a String
1. Default Constructor (initial capacity of 16):

2. With an Initial Capacity:

3. With a string

StringBuffer Methods

Method Description

append(String s) It is used to append the specified string with this


string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double) etc.

insert(int offset, It is used to insert the specified string with this string
String s) at the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.

replace(int It is used to replace the string from specified


startIndex, int startIndex and endIndex.
endIndex, String
str)

delete(int It is used to delete the string from specified startIndex


startIndex, int and endIndex.
endIndex)

reverse() is used to reverse the string.


Difference between String and StringBuffer in Java
S. STRING STRINGBUFFER
NO.

1 String is immutable. It is mutable.

2 It is slow in terms of executing the It is fast in terms of executing the


concatenation task. concatenation task.

3 Here the length of the string class is Here the length can be modified whenever
static. required, as it is dynamic in behaviour.

4 It is less efficient. It is more efficient in nature as compared to


the string class.

5 String consumes more as compared to StringBuffer uses less memory as compared


the stringbuffer. to the string.

5 It utilises a string constant pool to It prefers heap memory to store the objects.
store the values.

6 It overrides both equal() and It cannot override equal() and hashcode()


hashcode() techniques of object class. methods.
Enumeration (enum)
An enum is a special "class" that represents a group
of constants (unchangeable variables, like final variables).
To create an enum, use the enum keyword (instead of class or interface), and
separate the constants with a comma.

Defining an Enum
An enum in Java is defined using the enum keyword. Here’s a basic example:

In this example, Day is an enum that contains the days of the week as its
constants.

Using an Enum
You can use an enum just like any other type in Java. Here’s how you can use
the Day enum defined above:
Thread
Imagine you're making a delicious breakfast. Threads are like the different
tasks you can do at the same time:
• One thread (you) is making coffee: You boil water, add coffee
grounds, and pour it into a mug. This represents a single task within the
thread.
• Another thread (you again!) is scrambling eggs: You whisk eggs,
heat them in a pan, and season them. This is another task within the same
thread (you) but happening concurrently with making coffee.
• Maybe a third thread (your sibling) is toasting bread: They put
bread in the toaster, wait for it to pop, and butter it. This is a separate thread
(your sibling) working on their own task.
Key points from this example:
• You (the program) can handle multiple tasks (threads) at once, just
like making breakfast.
• Each thread can perform its own independent actions (making coffee,
scrambling eggs).
• Threads can sometimes share resources (like the kitchen space) but need
to be careful not to interfere with each other (e.g., accidentally knocking
over the coffee while grabbing toast).
This is a simplified analogy, but it captures the essence of threads in Java:
allowing your program to manage seemingly simultaneous tasks for
improved efficiency and responsiveness.

Building upon the breakfast analogy, let's connect it to threads in Java:


• You (the program) are like the main thread: This is the
primary thread that coordinates everything. In Java, it's the starting point of
your program's execution.
• Making coffee (or any single task) is like a method within the
thread: Each action within a thread can be represented as a method that
performs a specific function. In Java, these methods contain the code you
want the thread to execute.
• Multiple threads are like you and your sibling working on
breakfast together: Just like you can make coffee while your sibling toasts
bread, Java allows you to create separate threads that run concurrently.
• Sharing the kitchen (resources) is like threads accessing shared
data: In Java programs, threads might need to access and modify the same
data (like variables). Similar to how you might both need the spatula to
cook, threads need proper mechanisms (synchronization) to avoid conflicts
and ensure data consistency.
Here's a breakdown of how the breakfast tasks translate to Java concepts:
• Creating a Thread: Imagine you putting on an apron and grabbing
ingredients – that's like creating a new thread object in Java.• Starting a
Thread: When you actually begin making coffee (the task), it's like calling the
start() method on the thread object in Java. This signals the JVM to start
executing the thread's code (the method containing the coffee-making
instructions).
• Thread Execution: The process of making coffee (grinding, brewing,
pouring) is akin to the code running within your thread's method.
• Shared Resources: The kitchen space, utensils, and ingredients represent
shared resources in Java programs. Threads need to be synchronized when
accessing these resources to prevent issues like accidentally using the same
cup for both coffee and scrambled eggs.

Threads in Java
Threads are a fundamental concept in Java that enable a program to perform
multiple tasks apparently simultaneously. They represent a lightweight unit
of execution within a process. Unlike traditional processes that are
heavyweight and resource-intensive, threads share the same memory space
of the process, making them efficient for multitasking within a program.
Why Use Threads?
• Improved Responsiveness: By utilizing threads, your program can
remain responsive to user interaction even while executing long-running
tasks in the background. The main thread, responsible for handling user
interface elements, wouldn't be blocked by a time-consuming operation
running in another thread.
• Increased Efficiency: Threads allow you to leverage multi-core
processors effectively. By distributing tasks across multiple threads, you
can significantly improve the performance of your program, especially for
CPU-bound operations.
• Background Operations: Threads are well-suited for executing tasks
in the background without hindering the main program's flow. This can be
beneficial for activities like downloading files, network communication, or
playing music.

Creating Threads in Java


There are two primary approaches to create threads in Java:
1. Extending the Thread Class:
This approach involves creating a subclass that inherits from the
java.lang.Thread class. You need to override the run() method within your
subclass, which defines the code to be executed by the thread. Here's a
basic example:
2. Implementing the Runnable Interface:
This approach offers more flexibility as it allows your class to extend another
class while still being able to run as a thread. You create a class that
implements the java.lang.Runnable interface. The interface requires you to
implement the run() method, which contains the thread's execution code.
Here's an example:
Java

In both approaches, once you have your thread class or a class implementing
Runnable, you can create a Threadobject and call its start()method to initiate
thread execution. The run() method will be invoked automatically by the Java
Virtual Machine (JVM) in a separate thread of control.

Thread States
A thread in Java can exist in various states throughout its lifecycle:
• New: The initial state when a thread object is created.
• Runnable: The thread is ready to be scheduled for execution by
the JVM.
• Running: The thread is currently executing code.
• Waiting: The thread is waiting for a specific event to occur
before proceeding, such as waiting for user input or for another
thread to finish a task.
• Blocked: The thread is temporarily suspended due to
external factors like I/O operations or resource contention.
• Terminated: The thread has finished execution and its
resources have been released.
Thread Synchronization
When multiple threads access shared resources within a program, it's crucial
to ensure data consistency. This is achieved through thread synchronization
mechanisms like synchronized methods or blocks. Synchronization
guarantees that only one thread can access a particular code section or
resource at a time, preventing race conditions and data corruption.
Example: Thread Implementation
Here's a comprehensive example demonstrating both approaches for
creating threads in Java: Java

As you can see, the main thread continues executing while the other two
threads print their messages concurrently.
Remember, threads are a powerful concept, but improper use can lead to
complex debugging challenges. It's essential to understand synchronization
mechanisms and utilize best practices when working with threads in your
Java applications.

Method Overloading
Overloading occurs when two or more methods in the same class have the
same name but different parameters (different type or number of
parameters). It allows a class to have more than one method with the same
name but different implementations.

Method Overriding
Overriding occurs when a subclass provides a specific implementation for a
method that is already defined in its superclass. The method in the subclass
should have the same name, return type, and parameters as the method in
the superclass.

You might also like