Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

advance OOP with Java

notes made for myself

Uploaded by

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

advance OOP with Java

notes made for myself

Uploaded by

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

Introduction of Object Oriented Programming

Last Updated : 09 Feb, 2023



As the name suggests, Object-Oriented Programming or OOPs refers


to languages that use objects in programming. Object-oriented
programming aims to implement real-world entities like inheritance,
hiding, polymorphism, etc in programming. The main aim of OOP is
to bind together the data and the functions that operate on them so
that no other part of the code can access this data except that
function.
OOPs Concepts:
 Class
 Objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing
1. Class:
A class is a user-defined data type. It consists of data members and
member functions, which can be accessed and used by creating an
instance of that class. It represents the set of properties or methods
that are common to all objects of one type. A class is like a blueprint
for an object.
For Example: Consider the Class of Cars. There may be many cars
with different names and brands but all of them will share some
common properties like all of them will have 4 wheels, Speed Limit,
Mileage range, etc. So here, Car is the class, and wheels, speed
limits, mileage are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life
entities. An Object is an instance of a Class. When a class is defined, no
memory is allocated but when it is instantiated (i.e. an object is created)
memory is allocated. An object has an identity, state, and behavior. Each
object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to
know the type of message accepted and type of response returned by the
objects.
For example “Dog” is a real-life Object, which has some characteristics like
color, Breed, Bark, Sleep, and Eats.

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.

Key Features of Java


1. Platform Independent
Compiler converts source code to byte code and then the JVM executes
the bytecode generated by the compiler. This byte code can run on any
platform be it Windows, Linux, or macOS which means if we compile a
program on Windows, then we can run it on Linux and vice versa. Each
operating system has a different JVM, but the output produced by all the OS
is the same after the execution of the byte code. That is why we call java a
platform-independent language.
2. Object-Oriented Programming
Java is an object-oriented language, promoting the use
of objects and classes. Organizing the program in the terms of a collection
of objects is a way of object-oriented programming, each of which represents
an instance of the class.

The four main concepts of Object-Oriented programming are:


 Abstraction
 Encapsulation
 Inheritance
 Polymorphism
3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar
with C or C++. It eliminates complex features like pointers and multiple
inheritances, making it easier to write, debug, and maintain code.
4. Robustness
Java language is robust which means reliable. It is developed in such a
way that it puts a lot of effort into checking errors as early as possible, that is
why the java compiler is able to detect even those errors that are not easy to
detect by another programming language. The main features of java that
make it robust are garbage collection, exception handling, and memory
allocation.
5. Security
In java, we don’t have pointers, so we cannot access out-of-bound
arrays i.e. it shows ArrayIndexOutOfBound Exception if we try to do so.
That’s why several security flaws like stack corruption or buffer overflow are
impossible to exploit in Java. Also, java programs run in an environment that
is independent of the os(operating system) environment which makes java
programs more secure.
6. Distributed
We can create distributed applications using the java programming
language. Remote Method Invocation and Enterprise Java Beans are used
for creating distributed applications in java. The java programs can be easily
distributed on one or more systems that are connected to each other through
an internet connection.

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.

Object Oriented Programming (OOPs) Concept


in Java



As the name suggests, Object-Oriented Programming or Java
OOPs concept refers to languages that use objects in programming,
they use objects as a primary source to implement what is to
happen in the code. Objects are seen by the viewer or user,
performing tasks you assign.
Object-oriented programming aims to implement real-world
entities like inheritance, hiding, polymorphism, etc. in
programming. The main aim of OOPs is to bind together the data
and the functions that operate on them so that no other part of the
code can access this data except that function.

Object-Oriented Programming is the backbone of Java. Mastering OOP


concepts like inheritance, encapsulation, and polymorphism is critical for
writing scalable Java code. The Java Programming Course takes you
through these concepts step by step, providing practical examples that
enhance your learning.
Example of OOPs Implementation in Java:
1

// Java Program to Demonstrate


2

// Use of Object and Classes


3

import java.io.*;
4

class Numbers {
6

// Properties
7

private int a;
8

private int b;
9

10

// Methods
11

public void sum(){


12

System.out.println(a+b);
13

}
14

15

public void sub(){


16

System.out.println(a-b);
17

}
18

19

public static void main (String[] args) {


20

21

// Creating Instance of Class


22

// Object
23

Numbers obj=new Numbers();


24

25

// Assigning Values to the Properties


26

obj.a=1;
27

obj.b=2;
28

29

// Using the Methods


30

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.

// Java Program to demonstrate


// Use of Class and Objects

// 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;
}

Static void get () {


System.out.println ("Employee name is: " +Employee name );
System.out.println ("Employee CTC is: " + Employee salary);
}

// Main Method
Public static void main (String args []) {
GFG.set ("Rathod Avinash", 10000.0f);
GFG.get();
}
}

Pillars of OOPS in Java


Let us now discuss the 4 pillars of OOPs:
1. Abstraction
Data Abstraction is the property by virtue of which only the essential details
are displayed to the user. The trivial or non-essential units are not displayed
to the user. Ex: A car is viewed as a car rather than its individual
components.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object, ignoring the irrelevant details. The
properties and behaviors of an object differentiate it from other objects of
similar type and also help in classifying/grouping the object.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the car speed or applying brakes will
stop the car, but he does not know how on pressing the accelerator, the
speed is actually increasing. He does not know about the inner mechanism
of the car or the implementation of the accelerators, brakes etc. in the car.
This is what abstraction is.

Note: In Java, abstraction is achieved by interfaces and abstract classes.


We can achieve 100% abstraction using interfaces.
Below is the implementation of abstraction using Abstract class:
Java

// abstract class
2

Abstract class GFG {


3

// abstract methods declaration


4

Abstract void add ();


5

Abstract void mul();


6

Abstract void div ();


7

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

// Encapsulation using private modifier


2

// Employee class contains private data


4

// called employee id and employee name


5

Class Employee {
6

private int empid;


7

Private String ename;


8

// Accessing the Element


10

// Using Method
11

Public int get_id(){


12

return empid;
13

}
14

15

Public String get name () {


16
return get name;
17

}
18

To learn more about topic refer to Encapsulation in Java article.


3. Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It
is the mechanism in Java by which one class is allowed to inherit the
features (fields and methods) of another class. We are achieving inheritance
by using extends keyword. Inheritance is also known as “is-a” relationship.
Let us discuss some frequently used important terminologies:
 Superclass: The class whose features are inherited is known as
superclass (also known as base or parent class).
 Subclass: The class that inherits the other class is known as subclass
(also known as derived or extended or child class). The subclass can add
its own fields and methods in addition to the superclass fields and
methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class that includes
some of the code that we want, we can derive our new class from the
existing class. By doing this, we are reusing the fields and methods of the
existing class.
Below is the implementation of Inheritance in Java:
Java
1

//base class or parent class or super class


2

class A{
3

//parent class methods


4

Void method1 () {}
5

Void method2 () {}
6

}
7
8

//derived class or child class or base class


9

Class B extends A {//Inherits parent class methods


10

//child class methods


11

Void method3 () {}
12

Void method4 () {}
13

To learn more about topic refer to Inheritance in Java article.


4. Polymorphism
It refers to the ability of object-oriented programming languages to
differentiate between entities with the same name efficiently. This is done by
Java with the help of the signature and declaration of these entities. The
ability to appear in many forms is called polymorphism.
Below is the implementation of the Polymorphism:
Java
1

Sleep (1000) //Millis


2

Sleep (1000, 2000) //millis,nanos

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

// Java Program to Demonstrate


2

// Method Overloading and Overriding


3

// Parent Class
5

Class Parent {
6

// Method Declared
8

Public void func(){


9

System.out.println ("Parent Method func");


10

}
11

12

// Method Overloading
13

Public void func (int a){


14

System.out.println ("Parent Method func” + a);


15

}
16

}
17
18

// Child Class
19

Class Child extends Parent {


20

21

// Method Overriding
22

@Override
23

Public void func (int a){


24

System.out.println ("Child Method” + a);


25

}
26

}
27

28

// Main Method
29

public class Main {


30

Public static void main (String args []) {


31

Parent obj1 = new Parent ();


32

obj1.func ();
33

obj1.func (5);
34

35

Child obj2 = new Child ();


36

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

Classes and Objects in Java


Last Updated : 03 Sep, 2024



In Java, classes and objects are basic concepts of Object Oriented


Programming (OOPs) that are used to represent real-world concepts
and entities. The class represents a group of objects having similar
properties and behavior. For example, the animal type Dog is a
class while a particular dog named Tommy is an object of
the Dog class.
In this article, we will discuss Java objects and classes and how to
implement them in our program.
Java Classes
A class in Java is a set of objects which shares common
characteristics/ behavior and common properties/ attributes. It is a
user-defined blueprint or prototype from which objects are created.
For example, Student is a class while a particular student named
Ravi is an object.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or
prototype from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of
methods.
4. A Class in Java can contain:
 Data member
 Method
 Constructor
 Nested Class
 Interface
Class Declaration in Java

Access modifier class <class name>


{
data member;
method;
constructor;
nested class;
interface;
}

Example of Java Class


// Java program to Illustrate Creation of Object
// using clone () method
// Main class
// implementing Cloneable interface
Class GFG implements Cloneable {

// 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.

Difference between Java Class and Objects


The differences between class and object in Java are as follows:
Class Object

Class is the blueprint of an object. It is


An object is an instance of the class.
used to create objects.
Class Object

No memory is allocated when a class Memory is allocated as soon as an


is declared. object is created.

An object is a real-world entity such as


A class is a group of similar objects.
a book, car, etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as


A class can only be declared once.
per requirement.

Objects of the class car can be BMW,


An example of class can be a car.
Mercedes, Ferrari, etc.

Arrays in Java


Arrays are fundamental structures in Java that allow us to store


multiple values of the same type in a single variable. They are
useful for managing collections of data efficiently. Arrays in Java
work differently than they do in C/C++. This article covers
the basics and in-depth explanations with examples of array
declaration, creation, and manipulation in Java.
Arrays are fundamental to Java programming. They allow you to
store and manipulate collections of data efficiently. If you’re looking
to get hands-on with more complex array operations and learn
advanced techniques, the Java Programming Course offers a
structured approach to mastering arrays in Java.
Let us start with an example of to print the elements of an
Array:
public class Main {

public static void main(String[] args)

// initializing array

Int [] arr = {1, 2, 3, 4, 5 };

// size of array

Int n = arr.length;

// traversing array

For (int i = 0; i < n; i++)

System.out.print (arr[i] + " ");

}
}

Basics of Arrays in Java


There are some basic operations we can start with as mentioned below:
1. Array Declaration
To declare an array in Java, use the following syntax:
type [] array Name;
 Type: The data type of the array elements (e.g., int, String).
 Array Name: The name of the array.
Note: The array is not yet initialized.
2. Create an Array
To create an array, you need to allocate memory for it using
the new keyword:
// creating an array of 5 integers
numbers = new int [5];
This statement initializes the numbers array to hold 5 integers. The default
value for each element is 0.
3. Access an Element of an Array
We can access array elements using their index, which starts from 0:
// Setting the first element of the array
numbers [0] = 10;
// accessing the first element
int first Element = numbers [0];
The first line sets the value of the first element to 10. The second line
retrieves the value of the first element.
4. Change an Array Element
To change an element, assign a new value to a specific index:
// Changing the first element to 20
numbers[0] = 20;
5. Array Length
We can get the length of an array using the length property:
// Getting the length of the array
int length = numbers.length;
Now, we have completed with basic operations so let us go through the in-
depth concepts of Java Arrays, through the diagrams, examples, and
explanations.
In-Depth Concepts of Java Array
Following are some important points about Java arrays.
Array Properties
 In Java, all arrays are dynamically allocated.
 Arrays may be stored in contiguous memory [consecutive memory
locations].
 Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using
size of.
 A Java array variable can also be declared like other variables with [] after
the data type.
 The variables in the array are ordered, and each has an index beginning
with 0.
 Java array can also be used as a static field, a local variable, or a method
parameter.
An array can contain primitives (int, char, etc.) and object (or non-primitive)
references of a class, depending on the definition of the array. In the case of
primitive data types, the actual values might be stored in contiguous memory
locations (JVM does not guarantee this behavior). In the case of class
objects, the actual objects are stored in a heap segment .

Note: This storage of arrays helps us randomly access the elements of an


array [Support Random Access].
Creating, Initializing, and Accessing an Arrays in Java
For understanding the array we need to understand how it actually works. To
understand this follow the flow mentioned below:
 Declare
 Initialize
 Access
i. Declaring an Array
The general form of array declaration is
Method 1:
type var-name[];
Method 2:
type[] var-name;
The element type determines the data type of each element that comprises
the array. Like an array of integers, we can also create an array of other
primitive data types like char, float, double, etc., or user-defined data types
(objects of a class).
Note: It is just how we can create is an array variable, no actual array
exists. It merely tells the compiler that this variable (int Array) will hold an
array of the integer type.
Now, Let us provide memory storage to this created array.
ii. Initialization an Array in Java
When an array is declared, only a reference of an array is created. The
general form of new as it applies to one-dimensional arrays appears as
follows:
Var-name = new type [size];
Here, type specifies the type of data being allocated, size determines the
number of elements in the array, and var-name is the name of the array
variable that is linked to the array. To use new to allocate an array, you
must specify the type and number of elements to allocate.
Example:
// declaring array
int intArray [];
// allocating memory to array
intArray = new int [20];
// combining both statements in one
int [] intArray = new int [20];
Note: The elements in the array allocated by new will automatically be
initialized to zero (for numeric types), false (for boolean), or null (for
reference types). Do refer to default array values in Java .
Obtaining an array is a two-step process. First, you must declare a variable
of the desired array type. Second, you must allocate the memory to hold the
array, using new, and assign it to the array variable. Thus, in Java, all
arrays are dynamically allocated.

Types of Arrays in Java


Java supports different types of arrays:
1. Single-Dimensional Arrays
These are the most common type of arrays, where elements are stored in a
linear order.
// A single-dimensional array
int [] singleDimArray = {1, 2, 3, 4, 5};
2. Multi-Dimensional Arrays
Arrays with more than one dimension, such as two-dimensional arrays
(matrices).
// A 2D array (matrix)
int[][] multiDimArray = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9} };
You can also access java arrays using for each loops.
Arrays of Objects in Java
An array of objects is created like an array of primitive-type data items in the
following way.
Syntax:
Method 1:
Object Type[] arrName;
Method 2:
Object Type arrName[];
Example of Arrays of Objects
Example 1: Here we are taking a student class and creating an array of
Student with five Student objects stored in the array. The Student objects
have to be instantiated using the constructor of the Student class, and their
references should be assigned to the array elements.

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

In an interface, you must initialize


In class, you can instantiate variables
variables as they are final but you can’t
and create an object.
create an object.

A class can contain concrete (with The interface cannot contain concrete
implementation) methods (with implementation) methods.

The access specifiers used with


In Interface only one specifier is used-
classes are private, protected, and
Public.
public.

Polymorphism in Java


The word ‘polymorphism’ means ‘having many forms’. In simple


words, we can define Java Polymorphism as the ability of a message
to be displayed in more than one form. In this article, we will learn
what is polymorphism and its type.
Real-life Illustration of Polymorphism in Java: A person can
have different characteristics at the same time. Like a man at the
same time is a father, a husband, and an employee. So the same
person possesses different behaviors in different situations. This is
called polymorphism.

What is Polymorphism in Java?


Polymorphism is considered one of the important features of
Object-Oriented Programming. Polymorphism allows us to perform a
single action in different ways. In other words, polymorphism allows
you to define one interface and have multiple implementations. The
word “poly” means many and “morphs” means forms, So it means
many forms.
Polymorphism enables Java developers to create more flexible and
reusable code. Understanding when and how to use it can make
your code more maintainable. The Java Programming
Course offers practical examples and projects that showcase the
power of polymorphism in real-world applications.
Types of Java Polymorphism
In Java Polymorphism is mainly divided into two types:
 Compile-time Polymorphism
 Runtime Polymorphism
Compile-Time Polymorphism in Java
It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.

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:

// Java Program for Method overloading

// by using Different Types of Arguments

// Class 1

// Helper class

Class Helper {

// Method with 2 integer parameters

Static int Multiply (int a, int b)

// Returns product of integer numbers

Return a * b;

// Method 2

// with same name but with 2 double parameters

Static double Multiply (double a, double b)

// Returns product of double numbers

Return a * b;
}

// Class 2

// Main class

Class GFG {

// Main driver method

Public static void main (String [] args)

// Calling method by passing

// input as in arguments

System.out.println (Helper. Multiply (2, 4));

System.out.println (Helper. Multiply (5.5, 6.3));

}
}

Subtypes of Compile-time Polymorphism


1. Function Overloading
It is a feature in C++ where multiple functions can have the same name but
with different parameter lists. The compiler will decide which function to call
based on the number and types of arguments passed to the function.
2. Operator Overloading
It is a feature in C++ where the operators such as +, -, *, etc. can be given
additional meanings when applied to user-defined data types.
3. Template
it is a powerful feature in C++ that allows us to write generic functions and
classes. A template is a blueprint for creating a family of functions or classes.
Runtime Polymorphism in Java
It is also known as Dynamic Method Dispatch. It is a process in which a
function call to the overridden method is resolved at Runtime. This type of
polymorphism is achieved by Method Overriding. Method overriding, on the
other hand, occurs when a derived class has a definition for one of the
member functions of the base class. That base function is said to
be overridden.

// Java Program for Method Overriding

// Class 1

// Helper class

Class Parent {

// Method of parent class

void Print()

// Print statement

System.out.println ("parent class");

// Class 2

// Helper class

Class subclass1 extends Parent {


// Method

void Print() { System.out.println("subclass1"); }

// Class 3

// Helper class

Class subclass2 extends Parent {

// Method

Void Print ()

// Print statement

System.out.println ("subclass2");

// Class 4

// Main class

Class GFG {
// Main driver method

Public static void main (String [] args)

// creating object of class 1

Parent a;

// Now we will be calling print methods

// inside main () method

a = new subclass1 ();

a.Print ();

a = new subclass2 ();

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 –

Polymorphism in Java is a concept that allows objects of different classes to


be treated as objects of a common class. It enables objects to behave
differently based on their specific class type.
Advantages of Polymorphism in Java
1. Increases code reusability by allowing objects of different classes to be
treated as objects of a common class.
2. Improves readability and maintainability of code by reducing the amount
of code that needs to be written and maintained.
3. Supports dynamic binding, enabling the correct method to be called at
runtime, based on the actual class of the object.
4. Enables objects to be treated as a single type, making it easier to write
generic code that can handle objects of different types.
Disadvantages of Polymorphism in Java
1. Can make it more difficult to understand the behavior of an object,
especially if the code is complex.
2. This may lead to performance issues, as polymorphic behavior may
require additional computations at runtime.
Inheritance in Java


Java, Inheritance is an important pillar of OOP(Object-Oriented


Programming). It is the mechanism in Java by which one class is
allowed to inherit the features(fields and methods) of another class.
In Java, Inheritance means creating new classes based on existing
ones. A class that inherits from another class can reuse the methods
and fields of that class. In addition, you can add new fields and
methods to your current class as well.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends
keyword indicates you are derived from an existing class. In other words,
“extends” refers to increased functionality.
Syntax:
Class Derived Class extends Base Class
{
//methods and fields
}
Inheritance in Java Example
Example: In the below example of inheritance, class Bicycle is a base class,
class MountainBike is a derived class that extends the Bicycle class and
class Test is a driver class to run the program.

// Java Program to illustrate Inheritance (concise)

import java.io.*;

// Base or Super Class

class Employee {
int salary = 60000;

// Inherited or Sub Class

class Engineer extends Employee {

int benefits = 10000;

// Driver Class

Class Gfg {

Public static void main (String args [])

Engineer E1 = new Engineer ();

System.out.println ("Salary: " + E1.salary

+ "\nBenefits : " + E1.benefits);

}
}

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.

Java Inheritance Types


Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It
inherits the properties and behavior of a single-parent class. Sometimes, it is
also known as simple inheritance. In the below figure, ‘A’ is a parent class
and ‘B’ is a child class. The class ‘B’ inherits all the properties of the class
‘A’.
// Java program to illustrate the
// concept of single inheritance
import java.io.*;
import java.lang.*;
import java.util.*;

// Parent class
class One {
public void print_geek()
{
System.out.println("Geeks");
}
}

class Two extends One {


public void print_for() { System.out.println("for"); }
}

// 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

// Java program to illustrate the


2

// concept of Hierarchical inheritance


3

class A {
5

public void print_A() { System.out.println("Class A"); }


6

}
7

class B extends A {
9

public void print_B() { System.out.println("Class B"); }


10

}
11

12

class C extends A {
13

public void print_C() { System.out.println("Class C"); }


14

}
15

16

class D extends A {
17

public void print_D() { System.out.println("Class D"); }


18

}
19

20

// Driver Class
21

public class Test {


22

public static void main(String[] args)


23

{
24

B obj_B = new B();


25

obj_B.print_A();
26

obj_B.print_B();
27

28

C obj_C = new C();


29

obj_C.print_A();
30

obj_C.print_C();
31

32

D obj_D = new D();


33

obj_D.print_A();
34

obj_D.print_D();
35

}
36

Output
Class A
Class B
Class A
Class C
Class A
Class D

4. Multiple Inheritance (Through Interfaces)


In Multiple inheritances, one class can have more than one superclass and
inherit features from all parent classes. Please note that Java
does not support multiple inheritances with classes. In Java, we can achieve
multiple inheritances only through Interfaces. In the image below, Class C is
derived from interfaces A and B.
Multiple Inheritance

Java
1

// Java program to illustrate the


2

// concept of Multiple inheritance


3

import java.io.*;
4

import java.lang.*;
5

import java.util.*;
6

interface One {
8

public void print_geek();


9

}
10
11

interface Two {
12

public void print_for();


13

}
14

15

interface Three extends One, Two {


16

public void print_geek();


17

}
18

class Child implements Three {


19

@Override public void print_geek()


20

{
21

System.out.println("Geeks");
22

}
23

24

public void print_for() { System.out.println("for"); }


25

}
26

27

// Drived class
28

public class Main {


29

public static void main(String[] args)


30

{
31

Child c = new Child();


32

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

Java IS-A type of Relationship


IS-A is a way of saying: This object is a type of that object. Let us see how
the extends keyword is used to achieve inheritance.
Java

Public class Solar System {


}
3

Public class Earth extends Solar System {


4

}
5

Public class Mars extends Solar System {


6

}
7

Public class Moon extends Earth {


8

}
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.

What is Static Data Structure?


Static data structures are characterized by their fixed size and predefined
memory allocation. This means that the amount of memory allocated to the
structure is determined at compile time and remains constant throughout
the program’s execution. Examples of static data structures include arrays.

Features of Static Data Structures:


There are many features of static data structures. Let’s discuss the most popular of
them:
 Memory Allocation: For static data structures, static memory is allocated at the
compile time by the compiler, which is stored in the stack memory of the
program.
 Memory Deallocation: Memory allocated to the static data structures deallocates
when they go out of scope or the program ends.
 Continuous Memory Allocation: As we have discussed above, continuous
memory is allocated to the static data structures, which means there is no need
to store the structural information of the data structure or explicit data variable
to store the information of the memory location.
Advantages of Static Data Structures:
 Static data structures have a fixed size and structure, making them simpler to
implement and understand.
 Since the size is known in advance, the memory can be allocated efficiently.
 The behavior of static data structures is more predictable, making them suitable
for real-time systems.
 Accessing elements in static data structures is generally faster than in dynamic
data structures.
Disadvantages of Static Data Structures:
 The size and structure of static data structures are fixed, which can lead to
inefficient memory usage if the data requirements change.
 Static data structures have a predefined size, limiting their ability to handle large
and varying amounts of data.
 If the data size is smaller than the allocated memory, the unused memory is
wasted.
 Expanding the size of a static data structure requires complex procedures, such as
creating a new, larger structure and copying the data.
Examples of Static Data Structures:
Array: An array is a collection of elements identified by index or key values. The size
of the array is specified at the time of creation and remains constant. For example, an
array of integers can be declared as int arr [8]; in C++, which creates an array of
size 8.

Public class Main {

Public static void main (String [] args)

// Declaration of an array of size 6

int [] array = new int[6];

// initialize and printing values of array elements

For (int i = 0; i < 6; i++) {

Array[i] = i;

System.out.print (array[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.

Features of Dynamic Data Structures:


There are many features of dynamic data structures. Let’s discuss the most
popular of them:
 Dynamic Memory Allocation: Dynamic data structures allocate memory
at runtime, rather than being pre-allocated at compile-time. This memory
is stored in the program’s heap.
 Flexible Memory Usage: Unlike static data structures, the memory used
by dynamic data structures is not limited to a fixed size. It can expand or
contract as needed during program execution.
 Manual Memory Management: The memory allocated to dynamic data
structures does not automatically deallocate when the structure goes out
of scope. The programmer is responsible for manually deallocating this
memory, often using functions like free() or delete(), to avoid memory
leaks.
 Non-Contiguous Memory: The memory locations used by dynamic data
structures are not guaranteed to be contiguous. This means additional
metadata must be stored to track the locations of each element within the
data structure.
Advantages of Dynamic Data Structures:
 Dynamic data structures can grow or shrink in size as needed, allowing
for efficient use of memory.
 They can allocate and deallocate memory dynamically, preventing
wastage of memory.
 Dynamic data structures can handle large and varying amounts of data
without pre-defining the size.
 They provide a simpler programming interface compared to static data
structures.
Disadvantages of Dynamic Data Structures:
 Dynamic memory allocation and deallocation can incur additional
overhead compared to static data structures.
 Dynamic data structures can be more complex to implement and maintain
than static data structures.
 Improper handling of dynamic memory can lead to memory leaks, which
can cause performance issues.
 The performance of dynamic data structures can be less predictable than
static data structures, especially in real-time systems.
Examples of Dynamic Data Structures:
Linked List : Linked Lists are linear data structures where the elements are
not stored in contiguous locations and every element is a separate object
with a data part and address part. The elements are linked using pointers
and addresses. Each element is known as a node. Due to the dynamicity
and ease of insertions and deletions, they are preferred over the arrays

Public class Linked List {

Int data;

Linked List next;

Public static void main (String [] args)

// creating a linked list

Linked List node1 = new Linked List();

node1.data = 1;
Linked List node2 = new Linked List ();

node2.data = 2;

Linked List node3 = new Linked List ();

node3.data = 3;

// linking all the nodes

node1.next = node2;

node2.next = node3;

node3.next = null;

// printing value of linked list

System.out.println (node1.data + " " + node2.data

+ " " + node3.data);

You might also like