advance OOP with Java
advance OOP with Java
3. Data Abstraction:
Data abstraction is one of the most essential and important features of
object-oriented programming. Data abstraction refers to providing only
essential information about the data to the outside world, hiding the
background details or implementation. Consider a real-life example of a man
driving a car. The man only knows that pressing the accelerators will
increase the speed of the car or applying brakes will stop the car, but he
does not know about how on pressing the accelerator the speed is
increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc. in the car. This is what
abstraction is.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is
the mechanism that binds together code and the data it manipulates. In
Encapsulation, the variables or data of a class are hidden from any other
class and can be accessed only through any member function of their class
in which they are declared. As in encapsulation, the data in a class is hidden
from other classes, so it is also known as data-hiding.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The
capability of a class to derive properties and characteristics from another
class is called Inheritance. When we write a class, we inherit properties from
other classes. So when we create a class, we do not need to write all the
properties and functions again and again, as these can be inherited from
another class that possesses it. Inheritance allows the user to reuse the
code whenever possible and reduce its redundancy.
6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more
than one form. For example, A person at the same time can have different
characteristics. Like a man at the same time is a father, a husband, an
employee. So the same person posses different behavior in different
situations. This is called polymorphism.
7. Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call
is decided at runtime. Dynamic binding means that the code associated with
a given procedure call is not known until the time of the call at run
time. Dynamic Method Binding One of the main advantages of inheritance is
that some derived class D has all the members of its base class B. Once D is
not hiding any of the public members of B, then an object of D can represent
B in any context where a B could be used. This feature is known as subtype
polymorphism.
8. Message Passing:
It is a form of communication used in object-oriented programming as well as
parallel programming. Objects communicate with one another by sending
and receiving information to each other. A message for an object is a request
for execution of a procedure and therefore will invoke a function in the
receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function, and the
information to be sent.
INTRODUCTION TO JAVA?
Java is a class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is
intended to let application developers Write Once and Run Anywhere
(WORA), meaning that compiled Java code can run on all platforms that
support Java without the need for recompilation. Java was developed
by James Gosling at Sun Microsystems Inc. in May 1995 and later
acquired by Oracle Corporation and is widely used for developing
applications for desktop, web, and mobile devices.
Java is known for its simplicity, robustness, and security features, making it a
popular choice for enterprise-level applications. Java applications are
compiled to byte code that can run on any Java Virtual Machine. The syntax
of Java is similar to C/C++.
Java makes writing, compiling, and debugging programming easy. It helps to
create reusable code and modular programs.
7. Multithreading
Java supports multithreading , enabling the concurrent execution of
multiple parts of a program. This feature is particularly useful for applications
that require high performance, such as games and real-time simulations.
8. Portability
As we know, java code written on one machine can be run on another
machine. The platform-independent feature of java in which its platform-
independent bytecode can be taken to any platform for execution makes java
portable. WORA(Write Once Run Anywhere) makes java application to
generates a ‘.class’ file that corresponds to our applications(program) but
contains code in binary format. It provides ease t architecture-neutral ease
as bytecode is not dependent on any machine architecture. It is the primary
reason java is used in the enterprising IT industry globally worldwide.
9. High Performance
Java architecture is defined in such a way that it reduces overhead during
the runtime and at some times java uses Just In Time (JIT) compiler where
the compiler compiles code on-demand basis where it only compiles those
methods that are called making applications to execute faster.
Essential Java Terminologies You Need to Know
Before learning Java, one must be familiar with these common terms of
Java.
1. Java Virtual Machine (JVM)
The JVM is an integral part of the Java platform, responsible for executing
Java bytecode. It ensures that the output of Java programs is consistent
across different platforms.
Writing a program is done by a java programmer like you and me.
The compilation is done by the JAVAC compiler which is a primary Java
compiler included in the Java development kit (JDK). It takes the Java
program as input and generates bytecode as output.
In the Running phase of a program, JVM executes the bytecode
generated by the compiler.
Now, we understood that the function of Java Virtual Machine is to execute
the bytecode produced by the compiler. Every Operating System has a
different JVM but the output they produce after the execution of bytecode is
the same across all the operating systems. This is why Java is known as
a platform-independent language.
2. Bytecode
Bytecode is the intermediate representation of Java code, generated by the
Java compiler. It is platform-independent and can be executed by the JVM.
3. Java Development Kit (JDK)
While we were using the term JDK when we learn about bytecode and JVM.
So, as the name suggests, it is a complete Java development kit that
includes everything including compiler, Java Runtime Environment (JRE),
Java Debuggers, Java Docs, etc. For the program to execute in java, we
need to install JDK on our computer in order to create, compile and run the
java program.
4. Java Runtime Environment (JRE)
JDK includes JRE. JRE installation on our computers allows the java
program to run, however, we cannot compile it. JRE includes a browser,
JVM, applet support, and plugins. For running the java program, a computer
needs JRE.
5. Garbage Collector
In Java, programmers can’t delete the objects. To delete or recollect that
memory JVM has a program called Garbage Collector. Garbage Collectors
can recollect the objects that are not referenced. So Java makes the life of a
programmer easy by handling memory management.
However, programmers should be careful about their code whether they
are using objects that have been used for a long time. Because Garbage
cannot recover the memory of objects being referenced.
6. Class Path
The Class path is the file path where the java runtime and Java compiler
look for .class files to load. By default, JDK provides many libraries. If you
want to include external libraries they should be added to the classpath.
Basically everything in java is represented in Class as an object including the
main function.
Advantages of Java
Platform independent: Java code can run on any platform that has
a Java Virtual Machine (JVM) installed, which means that applications
can be written once and run on any device.
Object-Oriented: Java is an object-oriented programming language,
which means that it follows the principles of encapsulation, inheritance,
and polymorphism.
Security: Java has built-in security features that make it a secure
platform for developing applications, such as automatic memory
management and type checking.
Large community: Java has a large and active community of developers,
which means that there is a lot of support available for learning and using
the language.
Enterprise-level applications: Java is widely used for developing
enterprise-level applications, such as web applications, e-commerce
systems, and database systems.
Disadvantages of Java
1. Performance: Java can be slower compared to other programming
languages, such as C++, due to its use of a virtual machine and automatic
memory management.
2. Memory management: Java’s automatic memory management can lead
to slower performance and increased memory usage, which can be a
drawback for some applications.
import java.io.*;
4
class Numbers {
6
// Properties
7
private int a;
8
private int b;
9
10
// Methods
11
System.out.println(a+b);
13
}
14
15
System.out.println(a-b);
17
}
18
19
21
// Object
23
25
obj.a=1;
27
obj.b=2;
28
29
obj.sum();
31
obj.sub();
32
}
33
Output
3
-1
It is a simple example showing a class Numbers containing two variables
which can be accessed and updated only by instance of the object created.
Java OOPs
Now that we have covered the basic prerequisites, we will move on to the 4
pillars of OOPs which are as follows. But, let us start by learning about the
different characteristics of an Object-Oriented Programming Language.
Table of Content
Java OOPs
o What is Class?
o What is Object?
Pillars of OOPS in Java
o 1. Abstraction
o 2. Encapsulation
o 3. Inheritance
o 4. Polymorphism
o Types of Polymorphism
What is Class?
A Class is a user-defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all
objects of one type. Using classes, you can create multiple objects with the
same behavior instead of writing their code multiple times. This includes
classes for objects occurring more than once in your code. In general, class
declarations can include these components in order:
1. Modifiers: A class can be public or have default access (Refer to this for
details).
2. Class name: The class name should begin with the initial letter
capitalized by convention.
3. Body: The class body is surrounded by braces, { }.
What is Object?
An Object is a basic unit of Object-Oriented Programming that represents
real-life entities. A typical Java program creates many objects, which as you
know, interact by invoking methods. The objects are what perform your code,
they are the part of your code visible to the viewer/user. An object mainly
consists of:
1. State: It is represented by the attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects
the response of an object to other objects.
3. Identity: It is a unique name given to an object that enables it to interact
with other objects.
4. Method: A method is a collection of statements that perform some
specific task and return the result to the caller. A method can perform
some specific task without returning anything. Methods allow us
to reuse the code without retyping it, which is why they are
considered time savers. In Java, every method must be part of some
class, which is different from languages like C, C++, and Python.
// Class Declared
Public class GFG {
// Properties Declared
Static String Employee name;
Static float Employee salary;
// Methods Declared
Static void set (String n, float p) {
Employee name = n;
Employee salary = p;
}
// Main Method
Public static void main (String args []) {
GFG.set ("Rathod Avinash", 10000.0f);
GFG.get();
}
}
// abstract class
2
To learn more about the Abstraction refer to the Abstraction in Java article
2. Encapsulation
It is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together the code and the data it manipulates.
Another way to think about encapsulation is that it is a protective shield that
prevents the data from being accessed by the code outside this shield.
Technically, in encapsulation, the variables or the data in a class is
hidden from any other class and can be accessed only through any
member function of the class in which they are declared.
In encapsulation, the data in a class is hidden from other classes, which is
similar to what data-hiding does. So, the terms “encapsulation” and
“data-hiding” are used interchangeably.
Encapsulation can be achieved by declaring all the variables in a class as
private and writing public methods in the class to set and get the values of
the variables.
Below is the implementation of Encapsulation in Java:
Java
1
Class Employee {
6
// Using Method
11
return empid;
13
}
14
15
}
18
class A{
3
Void method1 () {}
5
Void method2 () {}
6
}
7
8
Void method3 () {}
12
Void method4 () {}
13
Types of Polymorphism
Polymorphism in Java is mainly of 2 types as mentioned below:
1. Method Overloading
2. Method Overriding
Method Overloading and Method Overriding
1. Method Overloading: Also, known as compile-time polymorphism, is the
concept of Polymorphism where more than one method share the same
name with different signature (Parameters) in a class. The return type of
these methods can or cannot be same.
2. Method Overriding: Also, known as run-time polymorphism, is the
concept of Polymorphism where method in the child class has the same
name, return-type and parameters as in parent class. The child class
provides the implementation in the method already written.
Below is the implementation of both the concepts:
Java
1
// Parent Class
5
Class Parent {
6
// Method Declared
8
}
11
12
// Method Overloading
13
}
16
}
17
18
// Child Class
19
21
// Method Overriding
22
@Override
23
}
26
}
27
28
// Main Method
29
obj1.func ();
33
obj1.func (5);
34
35
obj2.func (4);
37
}
38
Output
Parent Method func
Parent Method func 5
Child Method 4
To know more about the topic refer the Polymorphism in Java article.
Advantage of OOPs over Procedure-oriented programming language
Object-oriented programming (OOP) offers several key advantages over
procedural programming:
OOP promotes code reusability: By using objects and classes, you can
create reusable components, leading to less duplication and more
efficient development.
OOP enhances code organization: It provides a clear and logical
structure, making the code easier to understand, maintain, and debug.
OOP supports the DRY (Don’t Repeat Yourself) principle: This
principle encourages minimizing code repetition, leading to cleaner, more
maintainable code. Common functionalities are placed in a single location
and reused, reducing redundancy.
OOP enables faster development: By reusing existing code and
creating modular components, OOP allows for quicker and more efficient
application development
// Method 1
@Override
Protected Object clone ()
Throws CloneNotSupportedException
{
// Super () keyword refers to parent class
Return super. Clone ();
}
String name = "GeeksForGeeks";
// Method 2
// main driver method
Public static void main (String [] args)
{
GFG obj1 = new GFG ();
// Try block to check for exceptions
Try {
GFG obj2 = (GFG) obj1.clone ();
System.out.println (obj2.name);
}
Catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
Components of Java Classes
In general, class declarations can include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for
details).
2. Class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by
convention).
4. Superclass (if any): The name of the class’s parent (superclass), if any,
preceded by the keyword extends. A class can only extend (subclass)
one parent.
5. Interfaces (if any): A comma-separated list of interfaces implemented by
the class, if any, preceded by the keyword implements. A class can
implement more than one interface.
6. Body: The class body is surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that
provide the state of the class and its objects, and methods are used to
implement the behavior of the class and its objects.
There are various types of classes that are used in real-time applications
such as nested classes, anonymous classes, and lambda expressions.
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and
represents real-life entities. Objects are the instances of a class that are
created to use the attributes and methods of a class. A typical Java program
creates many objects, which as you know, interact by invoking methods. An
object consists of:
1. State: It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects
the response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to
interact with other objects.
Arrays in Java
// initializing array
// size of array
Int n = arr.length;
// traversing array
}
}
What is interface?
An Interface in Java programming language is defined as an abstract type
used to specify the behavior of a class. An interface in Java is a blueprint of
a behavior. A Java interface contains static constants and abstract methods.
What are Interfaces in Java?
The interface in Java is a mechanism to achieve abstraction. Traditionally,
an interface could only have abstract methods (methods without a body) and
public, static, and final variables by default. It is used to achieve abstraction
and multiple inheritances in Java. In other words, interfaces primarily define
methods that other classes must implement. Java Interface also represents
the IS-A relationship.
To deepen your understanding of interfaces and how they are used in
modern Java applications, the Java Programming Course offers structured
lessons and coding exercises to solidify your learning.
In Java, the abstract keyword applies only to classes and methods,
indicating that they cannot be instantiated directly and must be implemented.
When we decide on a type of entity by its behavior and not via attribute we
should define it as an interface.
Class Interface
A class can contain concrete (with The interface cannot contain concrete
implementation) methods (with implementation) methods.
Polymorphism in Java
Method Overloading
When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can
be overloaded by changes in the number of arguments or/and a change in
the type of arguments.
Example 1:
// Class 1
// Helper class
Class Helper {
Return a * b;
// Method 2
Return a * b;
}
// Class 2
// Main class
Class GFG {
// input as in arguments
}
}
// Class 1
// Helper class
Class Parent {
void Print()
// Print statement
// Class 2
// Helper class
// Class 3
// Helper class
// Method
Void Print ()
// Print statement
System.out.println ("subclass2");
// Class 4
// Main class
Class GFG {
// Main driver method
Parent a;
a.Print ();
a.Print ();
}
}
Output
subclass1
subclass2
Explanation of the above code:
Here in this program, When an object of a child class is created, then the
method inside the child class is called. This is because The method in the
parent class is overridden by the child class. Since The method is
overridden, This method has more priority than the parent method inside the
child class. So, the body inside the child class is executed.
Subtype of Run-time Polymorphism
i. Virtual functions
It allows an object of a derived class to behave as if it were an object of the
base class. The derived class can override the virtual function of the base
class to provide its own implementation. The function call is resolved at
runtime, depending on the actual type of the object.
Diagram –
import java.io.*;
class Employee {
int salary = 60000;
// Driver Class
Class Gfg {
}
}
Output
Salary : 60000
Benefits : 10000
Illustrative image of the program:
In practice, inheritance, and polymorphism are used together in Java to achieve fast
performance and readability of code.
// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}
// Driver class
public class Main {
// Main function
Public static void main (String [] args)
{
Two g = new Two ();
g.print_geek ();
g.print_for ();
g.print_geek ();
}
}
Output
Geeks
For
Geeks
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and
as well as the derived class also acts as the base class for other classes. In
the below image, class A serves as a base class for the derived class B,
which in turn serves as a base class for the derived class C. In Java, a class
cannot directly access the grandparent’s members.
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for
more than one subclass. In the below image, class A serves as a base class
for the derived classes B, C, and D.
Java
class A {
5
}
7
class B extends A {
9
}
11
12
class C extends A {
13
}
15
16
class D extends A {
17
}
19
20
// Driver Class
21
{
24
obj_B.print_A();
26
obj_B.print_B();
27
28
obj_C.print_A();
30
obj_C.print_C();
31
32
obj_D.print_A();
34
obj_D.print_D();
35
}
36
Output
Class A
Class B
Class A
Class C
Class A
Class D
Java
1
import java.io.*;
4
import java.lang.*;
5
import java.util.*;
6
interface One {
8
}
10
11
interface Two {
12
}
14
15
}
18
{
21
System.out.println("Geeks");
22
}
23
24
}
26
27
// Drived class
28
{
31
c.print_geek();
33
c.print_for();
34
c.print_geek();
35
}
36
Output
Geeks
for
Geeks
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java
doesn’t support multiple inheritances with classes, hybrid inheritance
involving multiple inheritance is also not possible with classes. In Java, we
can achieve hybrid inheritance only through Interfaces if we want to involve
multiple inheritance to implement Hybrid inheritance.
However, it is important to note that Hybrid inheritance does not necessarily
require the use of Multiple Inheritance exclusively. It can be achieved
through a combination of Multilevel Inheritance and Hierarchical Inheritance
with classes, Hierarchical and Single Inheritance with classes. Therefore, it is
indeed possible to implement Hybrid inheritance using classes alone, without
relying on multiple inheritance type.
Hybrid Inheritance
}
5
}
7
}
Static and Dynamic Data Structures
Data structures are the fundamental building blocks of computer
programming. They determine how data is organized, stored, and
manipulated within a software application. There are two main categories
of data structures: static and dynamic. Static data structures have a
fixed size and are allocated in memory during compile-time,
while dynamic data structures can grow and shrink in size during
runtime. This article will provide an overview of the key differences
between static and dynamic data structures, their use cases, and the
trade-offs to consider when choosing between them.
Array[i] = i;
System.out.println ();
}
Output
0 1 2 3 4 5
In the above code: we declared an array of the fixed size. After that, we
initialize some value using a loop and printed them.
What is Dynamic Data Structure?
Dynamic data structures are flexible in size and can grow or shrink as
needed during program execution. This adaptability makes them suitable for
handling data of varying sizes or when the size is unknown beforehand.
Examples of dynamic data structures include linked lists, stacks,
queues, and trees.
Int data;
node1.data = 1;
Linked List node2 = new Linked List ();
node2.data = 2;
node3.data = 3;
node1.next = node2;
node2.next = node3;
node3.next = null;