oops
oops
• 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 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 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
► 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).
► 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
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
► 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
► 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
► 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
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'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
► 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
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.
► Definition:
► Resolved during compile time.
► Key Features:
► Same method name, different parameter lists.
► Definition:
► Resolved during runtime.
► 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
► 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 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
► 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