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

oops

The document introduces Object-Oriented Programming (OOP) as a programming paradigm that organizes software design around data or objects, emphasizing concepts like abstraction, inheritance, polymorphism, and encapsulation. It also covers Java as a high-level, robust, and secure object-oriented programming language, detailing its features, such as platform independence and security mechanisms. Additionally, the document discusses the fundamental components of Java, including classes, objects, data types, packages, and access modifiers.

Uploaded by

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

oops

The document introduces Object-Oriented Programming (OOP) as a programming paradigm that organizes software design around data or objects, emphasizing concepts like abstraction, inheritance, polymorphism, and encapsulation. It also covers Java as a high-level, robust, and secure object-oriented programming language, detailing its features, such as platform independence and security mechanisms. Additionally, the document discusses the fundamental components of Java, including classes, objects, data types, packages, and access modifiers.

Uploaded by

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

Unit 1

INTRODUCTION TO OBJECT ORIENTED


PROGRAMMING
What is Object-Oriented Programming?

► The word object-oriented is the combination of two words


i.e. object and oriented.
► The dictionary meaning of the object is an article or entity that exists in
the real world.
► The meaning of oriented is interested in a particular kind of thing or
entity.
► It is a programming pattern that rounds around an object or entity are
called object-oriented programming.
► It is basically a computer programming design philosophy or methodology that
organizes/ models software design around data, or objects rather than functions and
logic.
► An object is referred to as a data field that has unique attributes and behavior.
Everything in OOP is grouped as self-sustainable objects.
► An object is referred to as a data field that has unique attributes and behavior.
Everything in OOP is grouped as self-sustainable objects.
► It is the most popular programming model among developers.
► It is well suited for programs that are large, complex, and actively updated or
maintained.
► It simplifies software development and maintenance by providing major concepts
such as abstraction, inheritance, polymorphism, and encapsulation. These core
concepts support OOP.
Points to Remember

• Everything is an object
• Developer manipulates objects that uses message passing.
• Every object is an instance of a class.
• The class contains the attribute and behavior associated with an object.
Pillars of OOPs
Introduction to JAVA

► Java is a programming language and a platform.


► Java is a high level, robust, object-oriented and secure programming
language.
► Java was developed by Sun Microsystems in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak.
Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.
Objects and Classes in Java

► In object-oriented programming, object and class plays vital


role in programming.
► These are the two main pillars of OOP.
► Without object and class, we cannot create a program in Java.
What is an object?

An object is a real-word entity that has


state and behaviour.

An object is a tangible thing that can be


touch and feel, like a car or chair, etc. are
the example of objects.

The banking system is an example of an


intangible object.

Every object has a distinct identity, which is


usually implemented by a unique ID that
the JVM uses internally for identification.
Characteristics of an Object

• State: It represents the data (value) of an object.


• Behavior: It represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
• Identity: An object's identity is typically implemented via a unique ID. The ID's value is
not visible to the external user; however, it is used internally by the JVM to identify each
object uniquely.
► For example: Pen is an object. Its name is Reynolds; color is white, known as its state. It
is used to write, so writing is its behavior.
► An object is an instance of a class. A class is a template or blueprint from which
objects are created. So, an object is the instance(result) of a class.
► Object Definitions:
• An object is a real-world entity.
• An object is a runtime entity.
• The object is an entity which has state and behavior.
• The object is an instance of a class.
What is a Class?

► A class is a group of objects which have


common properties. It is a template or Fields: Variables stated inside a class that indicate the status
of objects formed from that class are called fields.
blueprint from which objects are created.
► It is a logical entity. It can't be physical. Methods: Methods are functions defined inside a class that
includes the actions or behaviors that objects of that class
are capable of performing.

Constructors: Constructors are unique methods that are used


to initialize class objects.

Blocks: Within a class, Java allows two different kinds of


blocks: instance blocks, commonly referred to as initialization
blocks and static blocks.

Nested Class and Interface: Java permits the nesting of


classes and interfaces inside other classes and interfaces.
Features of Java

► The primary objective of Java


programming language
creation was to make it portable,
simple and secure programming
language.
Simple

► Java is very easy to learn, and its syntax is simple, clean and easy to
understand. According to Sun Microsystem, Java language is a simple
programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
• There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
Object-oriented

► Java is an object-oriented programming language. Everything in Java is an object.


Object-oriented means we organize our software as a combination of different types of
objects that incorporate both data and behavior.
► Basic concepts of OOPs are:
❖ Object
❖ Class
❖ Inheritance
❖ Polymorphism
❖ Abstraction
❖ Encapsulation
Platform Independent

► Java is platform independent because it is different from other languages


like C, C++, etc. which are compiled into platform specific machines while
Java is a write once, run anywhere language.
► A platform is hardware or software environment in which a program runs.
► There are two types of platforms software-based and hardware-based. Java
provides a software-based platform.
► The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on top of other hardware-based
platforms. It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
► Java code can be executed on multiple platforms,
► For example: Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is
compiled by the compiler and converted into bytecode. This bytecode is a
platform-independent code because it can be run on multiple platforms,
i.e., Write Once and Run Anywhere (WORA).
Secured

► Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
⮚ Classloader: Classloader in Java is a part of the Java Runtime Environment
(JRE) which is used to load Java classes into the Java Virtual Machine
dynamically. It adds security by separating the package for the classes of the
local file system from those that are imported from network sources.
⮚ Bytecode Verifier: It checks the code fragments for illegal code that can
violate access rights to objects.
⮚ Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.
► Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS,
Cryptography, etc.
Robust

► Java is robust because:


• It uses strong memory management.
• There is a lack of pointers that avoids security problems.
• Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
• There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
Architecture-neutral

► Java is architecture neutral because there are no implementation


dependent features, for example, the size of primitive types is fixed.
► In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
High-performance

► Java is faster than other traditional interpreted programming


languages because Java bytecode is "close" to native code. It is still a
little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages,
e.g., C, C++, etc.

► Distributed
► Java is distributed because it facilitates users to create distributed
applications in Java. RMI and EJB are used for creating distributed
applications. This feature of Java makes us able to access files by calling
the methods from any machine on the internet.
Portable

► Java is portable because it facilitates you to carry the Java bytecode to any platform.
It doesn't require any implementation.

► Multi-threaded
► A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications, etc.

► Dynamic
► Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages,
i.e., C and C++.
First Program

► In Java, every application begins with a class name, and that class
must match the filename.
► Let's create our first Java file, called Main.java, which can be done in
any text editor (like Notepad).
► The file should contain a "Hello World" message, which is written with
the following code:
Compilation Flow
Parameters used in First Java
Program
► class keyword is used to declare a class in Java.
► public keyword is an access modifier that represents visibility. It means it is visible to
all.
► static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to
create an object to invoke the static method. The main() method is executed by
the JVM, so it does not require creating an object to invoke the main() method.
So, it saves memory.
► void is the return type of the method. It means it does not return any value.
► The main() method represents the starting point of the program.
► String[] args or String args[] is used for command line argument.
► System.out.println() is used to print statement on the console. System is a class, out
is an object of the PrintStream class, println() is a method of the PrintStream class.
Feature C++ Java
Multi-paradigm: Supports procedural, object-oriented, and generic Object-oriented with some functional
Paradigm
programming. programming features.
Platform-dependent: Code needs recompilation for different operating Platform-independent: Runs on JVM, "Write Once,
Platform Dependency
systems. Run Anywhere."
Automatic memory management with garbage

C++ vs Java
Memory Management Manual memory management using new and delete.
collection.
Does not support direct pointer manipulation (for
Pointers Fully supports pointers and allows direct memory access.
security and abstraction).

Supports single inheritance using classes; multiple


Inheritance Supports multiple inheritance using classes.
inheritance achieved via interfaces.
Complex syntax with explicit memory management and operator Simplified syntax, no operator overloading or
Syntax
overloading. explicit pointers.
Compiled into bytecode, which is interpreted by
Compilation Compiled directly into machine code (platform-specific executables).
the JVM.
Slower than C++ due to JVM overhead and
Execution Speed Generally faster due to direct machine code execution.
abstraction.
Provides the Standard Template Library (STL) for data structures and Rich standard library (Java API) with extensive
Standard Library
algorithms. built-in support for networking, GUIs, etc.
Robust exception handling; try-catch is
Exception Handling Provides exception handling but without a mandatory try-catch structure.
mandatory for checked exceptions.
Built-in multithreading support in the core
Threading Relies on libraries like POSIX or Boost for threading.
language.
Purely object-oriented (everything is part of a
Object Orientation Not purely object-oriented (supports both procedural and OOP features).
class, except primitives).
Operator Overloading Supports operator overloading. Does not support operator overloading.
More secure with no direct memory access and
Security Less secure due to pointers and manual memory management.
built-in safety features.
GUI Development Requires third-party libraries like Qt or WxWidgets. Native support through JavaFX and Swing.
Web applications, mobile development (via
System programming, game development, embedded systems,
Use Cases Android), enterprise software, and cross-platform
performance-critical applications.
applications.
Java Variables

► Variable is a name of memory location. There are three types of


variables in java: local, instance and static.
Data Types

► Definition: A data type specifies the type of data a variable can hold, such
as integers, floating-point numbers, characters, or objects.
► Categories:
► Primitive Data Types: Predefined by Java, lightweight.
► The primitive data types include boolean, char, byte, short, int, long, float
and double.
► Non-Primitive Data Types: User-defined or derived types, more complex.
► The non-primitive data types include Classes, Interfaces, and Arrays.
Data Types
Initial Values for Variables

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


Java Package

► A java package is a group of similar types of classes, interfaces and sub-


packages.
► Package in java can be categorized in two form, built-in package and user-
defined package.
► There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.
► Advantage of Java Package
► Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
► Java package provides access protection.
► Java package removes naming collision.
Built-in packages
How to access package from another
package?
► There are three ways to access the package from outside the package.

► import package.*;
► If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.
► The import keyword is used to make the classes and interface of another package accessible
to the current package.
► import package.classname;
► If you import package.classname then only declared class of this package will be accessible.
► fully qualified name.
► If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
► It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
► Note: If you import a package, subpackages will not be imported.
Access Modifiers in Java

► There are two types of modifiers in Java: access modifiers and non-access modifiers.
► The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or
class.
► There are four types of Java access modifiers:

► Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
► Default: The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
► Protected: The access level of a protected modifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.
► Public: The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
► Note: A class cannot be private or protected except nested class.
Java Access Modifiers

Access Modifier within class within package outside package outside package
by subclass
only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
this keyword in Java

► There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the
current object.
► this can be used to refer current class instance variable.
► The this keyword can be used to refer current class instance variable. If there is ambiguity between the
instance variables and parameters, this keyword resolves the problem of ambiguity.
► Note: It is better approach to use meaningful names for variables. So we use same name for instance variables and
parameters in real time, and always use this keyword.
► this can be used to invoke current class method (implicitly)
► this() can be used to invoke current class constructor.
► this can be passed as an argument in the method call.
► this can be passed as argument in the constructor call.
► this can be used to return the current class instance from the method.
► Reference: https://www.javatpoint.com/this-keyword
Constructors in Java

► In Java, a constructor is a block of codes similar to the method. It is called


when an instance of the class is created. At the time of calling constructor,
memory for the object is allocated in the memory.
► It is a special type of method which is used to initialize the object.
► Every time an object is created using the new keyword, at least one
constructor is called.
► It calls a default constructor if there is no constructor available in the class. In
such case, Java compiler provides a default constructor by default.
► Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because Java
compiler creates a default constructor if your class does not have any.
Rules for Creating Java Constructor

► There are following rules for defining a constructor:


► Constructor name must be the same as its class name.

► A Constructor must have no explicit return type.

► A Java constructor cannot be abstract, static, final, and synchronized.

► Note: We can use access modifiers while declaring a constructor. It controls the
object creation. In other words, we can have private, protected, public or default
constructor in Java.
Types of Java Constructors

► Java Default Constructor


► A constructor is called "Default Constructor" when it does
not have any parameter.
► If there is no constructor in a class, compiler
automatically creates a default constructor.
Java Parameterized Constructor

► A constructor which has a specific number of parameters is called a


parameterized constructor.
► The parameterized constructor is used to provide different values to
distinct objects. However, you can provide the same values also.
Method in Java

► A method is a block of code or collection of statements, or a set of code


grouped together to perform a certain task or operation.
► It is used to achieve the reusability of code.
► We write a method once and use it many times.
► We do not require to write code again and again.
► It also provides the easy modification and readability of code, just by
adding or removing a chunk of code.
► The method is executed only when we call or invoke it.
► The most important method in Java is the main() method.
Method Declaration
Method Declaration

► Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.
► Access Specifier: Access specifier or modifier is the access type of the method. It
specifies the visibility of the method. Java provides four types of access specifier: Public,
Private, Protected, Default
► Return Type: Return type is a data type that the method returns. It may have a primitive
data type, object, collection, void, etc. If the method does not return anything, we use
void keyword.
► Method Name: It is a unique name that is used to define the name of a method. It must
be corresponding to the functionality of the method. Suppose, if we are creating a
method for subtraction of two numbers, the method name must be subtraction(). A
method is invoked by its name.
► Parameter List: It is the list of parameters separated by a comma and enclosed in the
pair of parentheses. It contains the data type and variable name. If the method has no
parameter, left the parentheses blank.
► Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.
Naming a Method

► While defining a method, remember that the method name must be


a verb and start with a lowercase letter.
► If the method name has more than two words, the first name must be
a verb followed by adjective or noun. In the multi-word method name,
the first letter of each word must be in uppercase except the first
word. For example:
► Single-word method name: sum(), area()
► Multi-word method name: areaOfCircle(), stringComparision()
► It is also possible that a method has the same name as another
method name in the same class, it is known as method overloading.
Difference Between Constructor and
Method in Java
Java Constructor Java Method

A constructor is used to initialize the state of A method is used to expose the behavior of
an object. an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default


The method is not provided by the compiler in
constructor if we do not have any constructor
any case.
in a class.

The constructor's name must be same as the The method name may or may not be same
class name. as the class name.
Java Control Statements

► Java compiler executes the code from top to bottom.


► The statements in the code are executed according to the order in which they appear. However, Java provides statements that
can be used to control the flow of Java code.
► Such statements are called control flow statements. It is one of the fundamental features of Java, which provides a smooth flow of
program.
► Java provides three types of control flow statements.
► Decision Making statements
► if statements
► switch statement
► Loop statements
► do while loop
► while loop
► for loop
► for-each loop
► Jump statements
► break statement
► continue statement
Encapsulation in Java

► Encapsulation in Java is a process of wrapping code and data together


into a single unit, for example, a capsule which is mixed of several
medicines.
► We can create a fully encapsulated class in Java by making all the data
members of the class private.
► Now we can use setter and getter methods to set and get the data in
it.
Key Features of Encapsulation

► Data Hiding : The internal state of an object (its variables/fields) is hidden


from the outside world. Access to the fields is controlled through public
methods (getters and setters).
► Controlled Access : Fields are declared private, making them
inaccessible from outside the class. Access is provided through public
methods, allowing controlled modification of data.
► Improved Maintainability : By encapsulating data and providing
controlled access, the internal implementation can be changed without
affecting other parts of the program.
► Reusability and Modularity: Encapsulation improves code reuse and
keeps the implementation modular.
Method Overloading

► Method overloading in Java is the feature that


enables defining several methods in a class having
the same name but with different parameters lists.
► Math Operations:
► In a math class, you might have multiple methods
for adding numbers, each accepting a different
number of arguments
Method Overloading rules

► Different ways to overload the method


► By changing the no. of arguments

► By changing the datatype

► Why method overloading is not possible by changing the return type


► Can we overload the main method
► Yes

► method overloading with Type Promotion


Method Overloading and Type
Promotion
► One type is promoted to another implicitly if no matching
datatype is found.
► Byte can be promoted to short, int, long, float or double.
The short datatype can be promoted to int, long, float or
double. The char datatype can be promoted to int, long,
float or double and so on.
Advantages of method overloading

► Readability and Maintainability: Overloading allows methods to have the same name and different
parameter lists, which increases readability and comprehensibility of the code. It helps developers to
name the different functions in a good way so that other developers can easily understand the code and
maintain it.
► Code Reusability: To avoid using too many methods with different names even when their function is
similar, method overloading makes it possible to reuse method names but have different types or numbers
of parameters. It causes the code to be reusable and, therefore, reduces code duplication.
► Flexibility: Method overloading gives the developer an advantage in creating methods which can be
called with any number of different parameters types or numbers. It offers such flexibility to make APIs that
can be expanded to multiple utilities.
► Polymorphism: Method overloading is a key to the realization of polymorphism in the Java, which permits
objects of the same type to react differently to method calls depending on the method's arguments. This
behavior somewhat polymorphic, hence leads to modularity and extensibility of code.
► Simplifies API Design: In the case of API design, the method overload is simplifying the interface as it serves
multiple ways in which to interact with the same functionality. The API users can select the most
convenient method signature according to their needs and then create a more thoughtful and user-
centered interface as a result.
► Enhances Code Readability: Overloading methods creates an opportunity of having multifaceted
functions encapsulated within a class.
Disadvantages of method overloading

► Ambiguity: Overloading may result in ambiguity if two of more overloaded methods have the same
types of parameters. In such instances, the compiler cannot tell which method has to be invoked
based on argument alone therefore compilation error can occur.
► Complexity: Deepening the use of method overloading may make code complex, especially if there
are many overloaded methods with similar names but different patterns of parameters. Such
complexity raises the bar for apprehension of code and its maintenance, particularly for developers
who are knowledgeable about the codebase.
► Hidden Behavior: Similar APIs might have different outcomes and behaviors, which may confuse
the developers in such kind of situation. If such a utilization of class methods is not properly
documented or understood, then it may lead to unexpected outcomes or bugs in the code.
► Performance Overhead: Nonetheless, the contribution of performance impact of method
overloading is, in fact, negligible, however, the presence of the excessive use of overloaded methods
with complex parameter lists could lead to a slight performance overhead mainly due to method
resolution at runtime.
► Overuse: Some developers may bypass this rule completely and use method overloading too much
to avoid coming up with different method names for similar features. In comparison, excessive
calling of overloading methods carries the risk of code bloat and decreased code clarity, hence
making it harder to underpin each method purpose
Method Overriding

► If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
► Usage of Java Method Overriding
1. Method overriding is used to provide the specific implementation of a method that is
already provided by its superclass.
2. Method overriding is used for runtime polymorphism.
3. Method overriding allows subclasses to reuse and build upon the functionality
provided by their superclass, reducing redundancy and promoting modular code
design.
4. Subclasses can override methods to tailor them to their specific needs or to
implement specialized behavior that is unique to the subclass.
5. Method overriding enables dynamic method dispatch, where the actual method
implementation to be executed is determined at runtime based on the type of object,
supporting flexibility and polymorphic behavior.
Rules for Java Method Overriding

► Same Method Name: The overriding method in the subclass must have the same name as the method in the
superclass that it is overriding.
► Same Parameters: The overriding method must have the same number and types of parameters as the method in
the superclass. This ensures compatibility and consistency with the method signature defined in the superclass.
► IS-A Relationship (Inheritance): Method overriding requires an IS-A relationship between the subclass and the
superclass.
► Same Return Type or Covariant Return Type: The return type of the overriding method can be the same as the
return type of the overridden method in the superclass, or it can be a subtype of the return type in the superclass.
This is known as the covariant return type, introduced in Java 5.
► Access Modifier Restrictions: The access modifier of the overriding method must be the same as or less restrictive
than the access modifier of the overridden method in the superclass. Specifically, a method declared as public in
the superclass can be overridden as public or protected but not as private. Similarly, a method declared as
protected in the superclass can be overridden as protected or public but not as private. A method declared as
default (package-private) in the superclass can be overridden with default, protected, or public, but not as
private.
► No Final Methods: Methods declared as final in the superclass cannot be overridden in the subclass. This is
because final methods cannot be modified or extended.
► No Static Methods: Static methods in Java are resolved at compile time and cannot be overridden. Instead, they
are hidden in the subclass if a method with the same signature is defined in the subclass.
Method Overloading Vs. Method
Overriding
Aspect Method Overloading Method Overriding

Method overriding is used to provide the specific


Method overloading is used to increase the readability of the
Purpose and Intent implementation of the method that is already
program.
provided by its superclass.

Relationship between Method overriding occurs in two classes that have


Method overloading is performed within class.
Classes IS-A (inheritance) relationship.

In case of method overloading, parameters must be In case of method overriding, parameters must be
Parameter Requirements
different. the same.
Method overloading is the example of compile-time Method overriding is the example of runtime
Polymorphism Type
polymorphism. polymorphism.

In Java, method overloading can't be performed by changing


the return type of the method only. Return type can be the Return type must be the same or covariant in
Return Type Constraints
same or different in method overloading, but you must have method overriding.
to change the parameter.
Polymorphism

► Polymorphism in Java is a concept by which we can perform a single


action in different ways.
► Types of Polymorphism
► There are two types of polymorphism in Java:
1. compile-time polymorphism
2. runtime polymorphism.
Compile-Time Polymorphism

► Definition:
► Resolved during compile time.

► Achieved using method overloading.

► Key Features:
► Same method name, different parameter lists.

► Improves code readability and flexibility.


Runtime Polymorphism

► Definition:
► Resolved during runtime.

► Achieved using method overriding.

► Key Features:
► Involves inheritance and the @Override
annotation.
► Enables dynamic method dispatch.
Advantages of Polymorphism
► Code Reusability
► Polymorphism allows methods in subclasses to override methods in their superclass, enabling code reuse and
maintaining a consistent interface across related classes.
► Flexibility and Extensibility
► Polymorphism allows subclasses to provide their own implementations of methods defined in the superclass, making it
easier to extend and customize behavior without modifying existing code.
► Dynamic Method Invocation
► Polymorphism enables dynamic method invocation, where the method called is determined by the actual object type at
runtime, providing flexibility in method dispatch.
► Interface Implementation
► Interfaces in Java allow multiple classes to implement the same interface with their own implementations, facilitating
polymorphic behavior and enabling objects of different classes to be treated interchangeably based on a common interface.
► Method Overloading
► Polymorphism is also achieved through method overloading, where multiple methods with the same name but different
parameter lists can be defined within a class or its subclasses, enhancing code readability and allowing flexibility in
method invocation based on parameter types.
► Reduced Code Complexity:
► Polymorphism helps reduce code complexity by promoting a modular and hierarchical class structure, making it easier to
understand, maintain, and extend large-scale software systems.
Constructor overloading

► In Java, we can overload constructors like methods.


► The constructor overloading can be defined as the concept of having
more than one constructor with different parameters so that every
constructor can perform a different task.
Abstract Class

► Abstraction is a process of hiding the implementation details and


showing only functionality to the user.
► for example, sending SMS where we type the text and send the
message.
► It provide a blueprint for other teams to follow, and some methods remain
undefined.
► A class that is declared with the abstract keyword is known as an abstract
class in Java. It can have abstract and non-abstract methods.
Points to Remember
Syntax of Abstract Classes

► Shape is an abstract class with one abstract


method area() and one concrete method
display(). Subclasses of Shape must implement
the area() method, but they can inherit the
display() method.
Abstract Method in Java

► A method which is declared as abstract and


does not have implementation is known as an
abstract method.

Key Features of Abstract Classes

► Abstract Methods: Abstract classes can have abstract methods, which are
declared without a body. Subclasses must provide concrete implementations
for these methods.
► Concrete Methods: Abstract classes can also contain concrete methods with
defined behavior. Subclasses inherit these methods along with their
implementations.
► Cannot be Instantiated: Abstract classes cannot be instantiated directly. They
serve as a blueprint for other classes and must be extended to be used.
► Can Have Constructors: Abstract classes can have constructors, which are
invoked when a subclass object is created. These constructors are used to
initialize the state of the abstract class.
Super Keyword

► The super keyword in Java is a reference variable which is used to refer


immediate parent class object.
► Usage of Java super Keyword
► super can be used to refer immediate parent class instance variable.
► super can be used to invoke immediate parent class method.
► super() can be used to invoke immediate parent class constructor.
► Note: super() is added in each class constructor automatically by compiler if
there is no super() or this().
► The default constructor is provided by compiler automatically if there is no
constructor. it also adds super() as the first statement.
super is used to refer immediate
parent class instance variable.
Final Keyword

► The final keyword in java is used to restrict the user. The java final keyword
can be used in many context. Final can be used for:
► variable

► method

► class
Java final variable

► If you make any variable as final, you cannot


change the value of final variable(It will be
constant).
Java final method

► If you make any method as final, you cannot


override it.
Inheritance

► Inheritance in Java is a mechanism in which one object acquires all the


properties and behaviors of a parent object.
► Inheritance in Java enables a class to inherit properties and actions from
another class, called a superclass or parent class.
► A class derived from a superclass is called a subclass or child group.
Why to use inheritance in Java?

► For Method Overriding (so runtime polymorphism can be achieved).


► For Code Reusability.
► Terms used in Inheritance
► Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
► Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
► Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
► Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when
you create a new class. You can use the same fields and methods already
defined in the previous class.
► The extends keyword indicates that we are making a new class that
derives from an existing class. The meaning of "extends" is to
increase the functionality.
Inheritance Example

► Programmer is the subclass and Employee


is the superclass. The relationship between
the two classes is Programmer IS-A
Employee. It means that Programmer is a
type of Employee.
Types of Inheritance
► Note: Multiple
inheritance is
not supported in
Java through
class.
► In java
programming,
multiple and
hybrid
inheritance is
supported
through
interface only.
Benefits of Inheritance

► Code Reusability: Inherited members from a superclass can be reused in subclasses,


reducing redundant code and promoting a modular approach to software
development.

► Hierarchical Organization: Inheritance facilitates the creation of well-structured class


hierarchies, improving code readability and maintainability.

► Polymorphism: Subclasses can override superclass methods, allowing for polymorphic


behavior, where methods can behave differently based on the object type at runtime.

► Easier Maintenance: Changes made to a superclass automatically propagate to its


subclasses, ensuring consistency and simplifying maintenance efforts.
Java Arrays

► Java array is an object which contains elements of a similar data type.


► The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.
► Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
► Advantages
► Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
► Random access: We can get any data located at an index position.
► Disadvantages
► Size Limit: Arrays have a fixed size and do not grow dynamically at runtime.
Array Example
For-each Loop for Java Array

► We can also print the Java array using for-each loop. The Java for-each
loop prints the array elements one by one. It holds an array element in a
variable, then executes the body of the loop.
References

► https://www.javatpoint.com/object-and-class-in-java

You might also like