0% found this document useful (0 votes)
19 views39 pages

Unit 1 Java

The document discusses object-oriented programming concepts in Java including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also covers Java programming fundamentals like defining packages, compiling Java code, and the basic structure of a Java program.

Uploaded by

mabhay584
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
19 views39 pages

Unit 1 Java

The document discusses object-oriented programming concepts in Java including classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It also covers Java programming fundamentals like defining packages, compiling Java code, and the basic structure of a Java program.

Uploaded by

mabhay584
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 39

Unit 1 OOPS with JAVA

Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java Source File
Structure, and Compilation. Fundamental,
Programming Structures in Java: Defining Classes in Java, Constructors, Methods, Access
Specifies, Static, Final Members, Data types, Variables, Operators, Control Flow, Arrays &
String.
Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class,
Overriding, Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces, and Abstract
Class.
Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR Files
for Library Packages, Import and Static Import Naming Convention For Packages
.

1.1.1 OOPs (Object Oriented Programming System)

Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming
is amethodology or paradigm to design a program using classes and objects. It simplifies the
softwaredevelopment and maintenance by providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object
Any entity that has state and behavior is known as an object. For example: chair, pen,
table,keyboard, bike etc. It can be physical and logical.

Class
Collection of objects is called class. It is a logical entity.

Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example:
toconvince the customer differently, to draw something e.g. shape or rectangle etc. In java, we
use method overloading and method overriding to achieve polymorphism. Another example
can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:

JAVA Page 1
phone
call, we don't know the internal processing. In java, we use abstract class and interface to
achieve abstraction.

Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation.For example: capsule, it is wrapped with different medicines. A java class is
the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.
Data hiding - base class can decide to keep some data private so that it cannot be altered by
the derived class

1.1.2 Java Programming- History of Java


Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems'
Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java
and its widespread popularity, multiple configurations were built to suit various types of
platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is
guaranteed to be Write Once, Run Anywhere.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions
etc. There are given the major points that describes the history of java.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Javalanguage project in
June 1991. The small team of sun engineers called Green Team.
Originally designed for small, embedded systems in electronic appliances like set-top boxes.
Firstly, it was called "Greentalk" by James Gosling and file extension was .gt. After that, it
was called Oak and was developed as a part of the Greenproject.

1.1.3 Features of Java


There is given many features of java. They are also known as java buzzwords. The Java
Feature sgiven below are simple and easy to understand.
Java is −
 Object Oriented − In Java, everything is an Object. Java can be easily extended since
it is based on the Object model.
 Platform Independent − Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and interpreted by
the Virtual Machine (JVM) on whichever platform it is being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic concept of
OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the presence of
Java runtime system.

JAVA Page 2
 Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a
clean portability boundary, which is a POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
 Multithreaded − With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to construct
interactive applications that can run smoothly.
 Interpreted − Java byte code is translated on the fly to native machine instructions and
is not stored anywhere. The development process is more rapid and analytical since the linking
is an incremental and light-weight process.
 High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
 Distributed − Java is designed for the distributed environment of the internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is designed
to adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.

Popular Java Editors


To write your Java programs, you will need a text editor. There are even more sophisticated
IDEs available in the market. But for now, you can consider one of the following −
 Notepad − On Windows machine, you can use any simple text editor like Notepad
(Recommended for this tutorial), TextPad.
 Netbeans − A Java IDE that is open-source and free which can be downloaded
from https://www.netbeans.org/index.html.
 Eclipse − A Java IDE developed by the eclipse open-source community and can be
downloaded from https://www.eclipse.org/.

1.1.4 Life cycle of a Java program


Life cycle of a java program tells us what happens right from the point when we type source
code in a text editor to the point that source code is converted into machine code (0’s and
1’s).There are three main stages in the life cycle of a java program. They are:

 Editing the program


 Compiling the source code
 Executing the byte code

JAVA Page 3
First, you will start with typing the program in a text-editor (ex: notepad, notepad++, wordpad,
textedit etc). After completing editing of the program, we have to save the file. While saving the
file you should remember that the file must be saved with .java extension. For example, let’s
think that I had written a Java program which contains a single class Sample (more on classes
in future posts). It is a good convention to save the file with the name of the class. So, as per
my example, the file will be saved as Sample.java.

Second step is compilation. The name of the Java compiler is javac. The input to the compiler
is Java source code which is available in Sample.java. The output of the compiler is machine
independent or platform independent code which is known as bytecode. The file which is
generated after compilation is .class file. As per my example, the bytecode file will
be Sample.class.

Last step is execution. The bytecode generated by the compiler will be executed by Java
Virtual Machine (JVM). Input to the JVM is bytecode and output is machine code (0’s and 1’s)
which will be executed by the CPU of the local machine.

Here is an example of the Hello Java program to understand the class structure and features.
There are a few lines in the program, and the primary task of the program is to print Hello
Java text on the screen.

1.1.5 A Simple Java Program to Print "Hello Java"

//Name of this file will be "Hello.java"

public class Hello


{
/* Date: 2018-04-28
Description:
Writes the words "Hello Java" on the screen */

public static void main(String[] args)


{
System.out.println("Hello Java");
}
}

Program Output:

Hello Java
Here are the most important points to note about the Java programs:

 You have to keep in mind that, Java code is case sensitive.


 To write a Java program, you must have to define class first.
 The name of the class in Java (which holds the main method) is the name of the Java
program, and the same name will be given in the filename. As mentioned above in the sample
program; The name of the class is "Hello" in which the main method is, then this file will be
named "Hello.Java".

Let's Look into Various Parts of the Above Java Program

public class  This creates a class called Hello.


Hello  All class names must start with a capital letter.
 The public word means that it is accessible from any other classes.

JAVA Page 4
/* Comments */ The compiler ignores comment block. Comment can be used anywhere in the
program to add info about the program or code block, which will be helpful for
developers to understand the existing code in the future easily.
Braces Two curly brackets {...} are used to group all the commands, so it is known that
the commands belong to that class or method.
public static  When the main method is declared public, it means that it can also be
void main used by code outside of its class, due to which the main method is declared
public.
 The word static used when we want to access a method without
creating its object, as we call the main method, before creating any class
objects.
 The word void indicates that a method does not return a value. main()
is declared as void because it does not return a value.
 main is a method; this is a starting point of a Java program.

You will notice that the main method code has been moved to some spaces
left. It is called indentation which used to make a program easier to read and
understand.
String[] args It is an array where each element of it is a string, which has been named as
"args". If your Java program is run through the console, you can pass the input
parameter, and main() method takes it as input.
System.out.pri This statement is used to print text on the screen as output, where the
ntln(); system is a predefined class, and out is an object of the PrintWriter class
defined in the system. The method println prints the text on the screen with a
new line. You can also use print() method instead of println() method. All Java
statement ends with a semicolon.

When we talk about the Java applications, then it works only on those machines which have
JVM.

1.1.6 What is JVM?

 JVM, i.e., Java Virtual Machine.


 JVM is the engine that drives the Java code.
 Mostly in other Programming Languages, compiler produce code for a particular
system but Java compiler produce Bytecode for a Java Virtual Machine.
 When we compile a Java program, then bytecode is generated. Bytecode is the source
code that can be used to run on any platform.
 Bytecode is an intermediary language between Java source and the host system.
 It is the medium which compiles Java code to bytecode which gets interpreted on a
different machine and hence it makes it Platform/Operating system independent.

JVM's work can be explained in the following manner

 Reading Bytecode.
 Verifying bytecode.
 Linking the code with the library.

JAVA Page 5
JVM generates a .class(Bytecode) file, and that file can be run in any OS, but JVM should have
in OS because JVM is platform dependent.

Platform Independent

Java is called platform independent because of Java Virtual Machine. As different computers
with the different operating system have their JVM, when we submit a .class file to any
operating system, JVM interprets the bytecode into machine level language.

 JVM is the main component of Java architecture, and it is the part of the JRE (Java
Runtime Environment).
 A program of JVM is written in C Programming Language, and JVM is Operating
System dependent.
 JVM is responsible for allocating the necessary memory needed by the Java program.
 JVM is responsible for deallocating memory space.

JDK (Java SE Development Kit) Includes a complete JRE (Java Runtime Environment) plus tools
for developing, debugging, and monitoring Java applications. JDK is required to build and run
Java applications and applets.

These tools are the foundation of the Java Development Kit.

Javac

javac is the compiler for the Java programming language; it's used to compile .java file. It
creates a class file which can be run by using java command.

Example:

c:javac TestFile.java

java
When a class file has been created, the java command can be used to run the Java program.

Example:

c:java TestFile.class
Both run using the command prompt. .java is the extension for java source files which are
simple text files. After coding and saving it, the javac compiler is invoked for
creating .class files. As the .class files get created, the Java command can be used to run the
java program.

JAVA Page 6
javadoc
JavaDoc is an API documentation generator for the Java language, which generates
documentation in HTML format from Java source code.

appletviewer
appletviewer run and debug applets without a web browser, its standalone command-line
program to run Java applets.

jar
The jar is (manage Java archive) a package file format that contains class, text, images and
sound files for a Java application or applet gathered into a single compressed file.

1.7 Java Identifiers


All Java components require names. Names used for classes, variables, and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows −
 All identifiers should begin with a letter (A to Z or a to z), currency character ($) or an
underscore (_).
 After the first character, identifiers can have any combination of characters.
 A key word cannot be used as an identifier.
 Most importantly, identifiers are case sensitive.
 Examples of legal identifiers: age, $salary, _value, __1_value.
 Examples of illegal identifiers: 123abc, -salary.

1.1.7 Variable
A variable provides us with named storage that our programs can manipulate. Each variable
in Java has a specific type, which determines the size and layout of the variable's memory; the
range of values that can be stored within that memory; and the set of operations that can be
applied to the variable.
You must declare all variables before they can be used. Following is the basic form of a variable
declaration −
data type variable [ = value][, variable [ = value] ...] ;
Here data type is one of Java's datatypes and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java −
Example
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

There are three kinds of variables in Java −


 Local variables
 Instance variables
 Class/Static variables

Local Variables
 Local variables are declared in methods, constructors, or blocks.

JAVA Page 7
 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
 Access modifiers cannot be used for local variables.
 Local variables are visible only within the declared method, constructor, or block.
 Local variables are implemented at stack level internally.
 There is no default value for local variables, so local variables should be declared and
an initial value should be assigned before the first use.

Example
Here, age is a local variable. This is defined inside pupAge() method and its scope is limited
to only this method.

public class Test {


public void pupAge() {
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age);
}
public static void main(String args[]) {
Test test = new Test();
test.pupAge();
}
}
This will produce the following result −
Output
Puppy age is: 7

Instance Variables

 Instance variables are declared in a class, but outside a method, constructor or any
block.
 When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
 Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
 Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object's state that must be present throughout the
class.
 Instance variables can be declared in class level before or after use.
 Access modifiers can be given for instance variables.
 The instance variables are visible for all methods, constructors and block in the class.
Normally, it is recommended to make these variables private (access level). However, visibility
for subclasses can be given for these variables with the use of access modifiers.
 Instance variables have default values. For numbers, the default value is 0, for
Booleans it is false, and for object references it is null. Values can be assigned during the
declaration or within the constructor.
 Instance variables can be accessed directly by calling the variable name inside the
class. However, within static methods (when instance variables are given accessibility), they
should be called using the fully qualified name. ObjectReference.VariableName.

Class/Static Variables

 Class variables also known as static variables are declared with the static keyword in
a class, but outside a method, constructor or a block.

JAVA Page 8
 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
 Static variables are rarely used other than being declared as constants. Constants are
variables that are declared as public/private, final, and static. Constant variables never change
from their initial value.
 Static variables are stored in the static memory. It is rare to use static variables other
than declared final and used as either public or private constants.
 Static variables are created when the program starts and destroyed when the program
stops.
 Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
 Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during the
declaration or within the constructor. Additionally, values can be assigned in special static
initializer blocks.
 Static variables can be accessed by calling with the class
name ClassName.VariableName.
 When declaring class variables as public static final, then variable names (constants)
are all in upper case. If the static variables are not public and final, the naming syntax is the
same as instance and local variables.

Example
import java.io.*;
public class Employee {
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]) {
salary = 1000;
System.out.println(DEPARTMENT + "average salary:" + salary);
}
}
This will produce the following result −
Output
Development average salary:1000

Java - Basic Operators


Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators

JAVA Page 9
1.1.8 Data Types

Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:
Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
Java Primitive Data Types In Java language, primitive data types are the building blocks
of data manipulation. These are the most basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared


before its use. That is why we need to declare variable's type and name.

Java Variable Example: Add Two Numbers

class Simple
{
public static void main(String[] args)
{
int a=10;int b=10;
int c=a+b;
System.out.println(c);
}}

Data Type Size Description

Byte 1 byte Stores whole numbers from -128 to 127

Short 2 bytes Stores whole numbers from -32,768 to 32,767

Int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

Long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

Float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

Double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits

JAVA Page 10
Boolean 1 bit Stores true or false values

Char 2 bytes Stores a single character/letter or ASCII values

1.1.9 Java - Decision Making


Decision making structures have one or more conditions to be evaluated or tested by the
program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
Java programming language provides following types of decision making statements. Click the
following links to check their detail.

Statement & Description

if statement
An if statement consists of a boolean expression followed by one or more
statements.

if...else
An if statement can be followed by an optional else statement, which
statement
executes when the boolean expression is false.

nested if
You can use one if or else if statement inside another if or else
statement
if statement(s).

switch
A switch statement allows a variable to be tested for equality against a list of
statement
values.

The ? : Operator
We have covered conditional operator ? : in the previous chapter which can be used to
replace if...else statements. It has the following general form −
Exp1 ? Exp2 : Exp3;
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
To determine the value of the whole expression, initially exp1 is evaluated.
 If the value of exp1 is true, then the value of Exp2 will be the value of the whole
expression.
 If the value of exp1 is false, then Exp3 is evaluated and its value becomes the value of
the entire expression.

1.1.10 Java - Loop Control


There may be a situation when you need to execute a block of code several number of times.
In general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

JAVA Page 11
Java programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.

Sr.No. Loop & Description

1 while loop
Repeats a statement or group of statements while a given condition is true. It tests the
condition before executing the loop body.

2 for loop
Execute a sequence of statements multiple times and abbreviates the code that
manages the loop variable.

3 do...while loop
Like a while statement, except that it tests the condition at the end of the loop body.

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves
a scope, all automatic objects that were created in that scope are destroyed.
Java supports the following control statements. Click the following links to check their detail.

Sr.No. Control Statement & Description

1 break statement
Terminates the loop or switch statement and transfers execution to the statement
immediately following the loop or switch.

2 continue statement
Causes the loop to skip the remainder of its body and immediately retest its condition
prior to reiterating.

Enhanced for loop in Java


As of Java 5, the enhanced for loop was introduced. This is mainly used to traverse collection
of elements including arrays.
Syntax
Following is the syntax of enhanced for loop −
for(declaration : expression) {
// Statements
}
 Declaration − The newly declared block variable, is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block and
its value would be the same as the current array element.
 Expression − This evaluates to the array you need to loop through. The expression
can be an array variable or method call that returns an array.

JAVA Page 12
Example
public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};

for( String name : names ) {


System.out.print( name );
System.out.print(",");
}
}
}
This will produce the following result −
Output
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,

1.1.11 Java - Strings Class

Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.

Creating Strings
The most direct way to create a string is to write −
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with
its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has 11 constructors that allow you to provide the initial value of
the string using different sources, such as an array of characters.
Example
public class StringDemo {

public static void main(String args[]) {


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };
String helloString = new String(helloArray);
System.out.println( helloString );
}
}

JAVA Page 13
This will produce the following result −
Output
hello.
Note − The String class is immutable, so that once it is created a String object cannot be
changed. If there is a necessity to make a lot of modifications to Strings of characters, then
you should use String Buffer & String Builder Classes.
String Length
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the number
of characters contained in the string object.
The following program is an example of length(), method String class.

public class StringDemo {

public static void main(String args[]) {


String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This will produce the following result − Output String Length is : 17
Concatenating Strings
The String class includes a method for concatenating two strings −
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can also use
the concat() method with string literals, as in −
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in −
"Hello," + " world" + "!"
which results in − "Hello, world!"
Let us look at the following example −

public class StringDemo {

public static void main(String args[]) {


String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
This will produce the following result Output
Dot saw I was Tod

JAVA Page 14
1.1.13 Java - Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using
indexed variables.
Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array
variable −
Syntax
dataType[] arrayRefVar; // preferred way.
or
dataType arrayRefVar[]; // works but not preferred way.
Note − The style dataType[] arrayRefVar is preferred. The style dataType
arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate
C/C++ programmers.
Example
The following code snippets are examples of this syntax −

double[] myList; // preferred way.


or
double myList[]; // works but not preferred way.

Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
 It creates an array using new dataType[arraySize].
 It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below −
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows −
dataType[] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they
start from 0 to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList −

double[] myList = new double[10];

JAVA Page 15
Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.

Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of
the elements in an array are of the same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize, and process arrays −

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}}
This will produce the following result −
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5

JAVA Page 16
1.1.14 The for each Loops
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables
you to traverse the complete array sequentially without using an index variable.
Example
The following code displays all the elements in the array myList −

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (double element: myList) {
System.out.println(element);
}
}
}

Passing Arrays to Methods


Just as you can pass primitive type values to methods, you can also pass arrays to methods.
For example, the following method displays the elements in an int array −
Example
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes the
printArray method to display 3, 1, 2, 6, 4, and 2 −
Example
printArray(new int[]{3, 1, 2, 6, 4, 2});

JAVA Page 17
Module 2: Java - Object and Classes

 JAVA Class − A class can be defined as a template/blueprint that describes the


behavior/state that the object of its type support.

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.

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


class Student {
// data member (also instance variable)
int id;
// data member (also instance variable)
String name;

public static void main(String args[])


{
// creating an object of
// Student
Student s1 = new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}}

JAVA Page 18
Components of Java Classes

1. Modifiers: A class can be public or has default access.


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

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.
Example of an object: dog

Java Objects

Objects correspond to things found in the real world. For example, a graphics program may
have objects such as “circle”, “square”, and “menu”. An online shopping system might have
objects such as “shopping cart”, “customer”, and “product”.
Note: When we create an object which is a non primitive data type, it’s always allocated on
the heap memory.
Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances
share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.
Dog tuffy;

Ways to Create an Object of a Class

JAVA Page 19
Using new keyword
It is the most common and general way to create an object in Java.
Example:
// creating object of class Test
Test t = new Test();

1.2.1 Access Modifiers in Java

in Java, Access modifiers help to restrict the scope of a class, constructor, variable, method,
or data member. It provides security, accessibility, etc to the user depending upon the access
modifier used with the element. Let us learn about Java Access Modifiers, their types, and the
uses of access modifiers in this article.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public

1. Default Access Modifier

When no access modifier is specified for a class, method, or data member – It is said to be
having the default access modifier by default. The data members, classes, or methods that
are not declared using any access modifiers i.e. having default access modifiers are
accessible only within the same package.

Program 1:

// Java program to illustrate default modifier


package p1;
// Class Cse is having Default access modifier
class Cse
{
void display()
{
System.out.println("Hello World!");
}
}

2. Private Access Modifier

The private access modifier is specified using the keyword private. The methods or data
members declared as private are accessible only within the class in which they are declared.
 Any other class of the same package will not be able to access these members.
 Top-level classes or interfaces can not be declared as private because
 private means “only visible within the enclosing class”.
 protected means “only visible within the enclosing class and any subclasses”
Hence these modifiers in terms of application to classes, apply only to nested classes and not
on top-level classes
In this example, we will create two classes A and B within the same package p1. We will
declare a method in class A as private and try to access this method from class B and see the
result.
// Java program to illustrate error while
// using class from different package with
// private modifier

JAVA Page 20
package p1;

class A
{
private void display()
{
System.out.println("GeeksforGeeks");
}
}

class B
{
public static void main(String args[])
{
A obj = new A();
// Trying to access private method
// of another class
obj.display();
}
}
Output:
error: display() has private access in A
obj.display();

3. Protected Access Modifier

The protected access modifier is specified using the keyword protected.


The methods or data members declared as protected are accessible within the same
package or subclasses in different packages.
In this example, we will create two packages p1 and p2. Class A in p1 is made public, to
access it in p2. The method display in class A is protected and class B is inherited from class
A and this protected method is then accessed by creating an object of class B.
Public Access modifier
The public access modifier is specified using the keyword public.
 The public access modifier has the widest scope among all other access modifiers.
 Classes, methods, or data members that are declared as public are accessible from
everywhere in the program. There is no restriction on the scope of public data members.

Program :

package p1;
public class A
{
public void display()
{
System.out.println("GeeksforGeeks");
}
}

JAVA Page 21
1. 2.2 Java Constructors

In Java, a Constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling the constructor, memory for the object is allocated
in the memory. It is a special type of method that is used to initialize the object. Every time an
object is created using the new() keyword, at least one constructor is called.
How Java Constructors are Different From Java Methods?
 Constructors must have the same name as the class within which it is defined it is not
necessary for the method in Java.
 Constructors do not return any type while method(s) have the return type or void if
does not return any value.
 Constructors are called only once at the time of Object creation while method(s) can
be called any number of times.

class Cse
{
.......
// A Constructor
Cse() {
}
.......
}// We can create an object of the above class
// using the below statement. This statement
// calls above constructor.
Cse obj = new Cse();

Each time an object is created using a new() keyword, at least one constructor (it could be
the default constructor) is invoked to assign initial values to the data members of the same
class.

Rules for writing constructors are as follows:

 The constructor(s) of a class must have the same name as the class name in which it
resides.
 A constructor in Java can not be abstract, final, static, or Synchronized.
 Access modifiers can be used in constructor declaration to control its access i.e which
other class can call the constructor.

Types of Constructors in Java

primarily there are two types of constructors in Java are mentioned below:
 Default Constructor
 Parameterized Constructor

Default Constructor in Java

A constructor that has no parameters is known as default the constructor. A default constructor
is invisible. And if we write a constructor with no arguments, the compiler does not create a
default constructor. It is taken out. It is being overloaded and called a parameterized
constructor. The default constructor changed into the parameterized constructor. But
Parameterized constructor can’t change the default constructor

Parameterized Constructor in Java

A constructor that has parameters is known as parameterized constructor. If we want to


initialize fields of the class with our own values, then use a parameterized constructor.

JAVA Page 22
1.2.3 Constructor overloading in Java

In Java, we can overload constructors like methods. The constructor overloading can be defined
as the concept of having more than one constructor with different parameters so that every
constructor can perform a different task. Consider the following Java program, in which we have
used different constructors in the class

public class Student {


//instance variables of the class
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n)
{ id = i; name = n; }

public static void main(String[] args) {


//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
System.out.println("\nParameterized Constructor values: \n");
Student student = new Student(10, "David");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.name);
}
}

1.2.4 static Keyword in Java

The static keyword in Java is mainly used for memory management. The static keyword in
Java is used to share the same variable or method of a given class. The users can apply static
keywords with variables, methods, blocks, and nested classes. The static keyword belongs to
the class than an instance of the class. The static keyword is used for a constant variable or
a method that is the same for every instance of a class.
The static keyword is a non-access modifier in Java that is applicable for the following:
1. Blocks
2. Variables
3. Methods
4. Classes

Note: To create a static member(block, variable, method, nested class), precede its
declaration with the keyword static.

JAVA Page 23
some characteristics of the static keyword in Java:
 Shared memory allocation: Static variables and methods are allocated memory
space only once during the execution of the program. This memory space is shared among
all instances of the class, which makes static members useful for maintaining global state or
shared functionality.
 Accessible without object instantiation: Static members can be accessed without
the need to create an instance of the class. This makes them useful for providing utility
functions and constants that can be used across the entire program.
 Associated with class, not objects: Static members are associated with the class,
not with individual objects. This means that changes to a static member are reflected in all
instances of the class, and that you can access static members using the class name rather
than an object reference.
 Cannot access non-static members: Static methods and variables cannot access
non-static members of a class, as they are not associated with any particular instance of the
class.
 Can be overloaded, but not overridden: Static methods can be overloaded, which
means that you can define multiple methods with the same name but different parameters.
However, they cannot be overridden, as they are associated with the class rather than with a
particular instance of the class.

When a member is declared static, it can be accessed before any objects of its class are
created, and without reference to any object. For example, in the below java program, we are
accessing static method m1() without creating any object of the Test class.

class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}

public static void main(String[] args)


{
// calling m1 without creating
// any object of class Test
m1();
}
}

When a variable is declared as static, then a single copy of the variable is created and
shared among all objects at the class level. Static variables are, essentially, global variables.
All instances of the class share the same static variable.

Important points for static variables:


 We can create static variables at the class level only.
 static variables are executed in the order they are present in a program.

JAVA Page 24
Class Test
{
// static variable
static int a = m1();
// static method
static int m1() {
System.out.println("from m1");
return 20;
}
public static void main(String[] args)
{
System.out.println("Value of a : "+a);
System.out.println("from main");
}
}

1.2.5 Final Keyword

final (lowercase) is a reserved keyword in java. We can’t use it as an identifier, as it is


reserved. We can use this keyword with variables, methods, and also with classes. The final
keyword in java has a different meaning depending upon whether it is applied to a variable,
class, or method.

final with Variables: The value of the variable cannot be changed once initialized.

class A {
public static void main(String[] args)
{
// Non final variable
int a = 5;

// final variable
final int b = 6;

// modifying the non final variable : Allowed


a++;

// modifying the final variable :


// Immediately gives Compile Time error.
b++;
}
}

final with Class: The class cannot be subclassed. Whenever we declare any class as final,
it means that we can’t extend that class or that class can’t be extended, or we can’t make a
subclass of that class.

final with Method: The method cannot be overridden by a subclass. Whenever we declare
any method as final, then it means that we can’t override that method.
class QQ {
final void rr() {}
public static void main(String[] args)
{
}
}

JAVA Page 25
class MM extends QQ {

// Here we get compile time error


// since can't extend rr since it is final.
void rr() {}
}

If a class is declared as final as by default all of the methods present in that class are
automatically final, but variables are not.

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

Why Do We Need Java Inheritance?


 Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through Inheritance. It is
one of the ways by which Java achieves Run Time Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.

Important Terminologies Used in Java Inheritance


 Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/ attributes. Class is not a real-world entity. It is just a template or blueprint
or prototype from which objects are created.
 Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
 Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, 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.

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.

import java.io.*;

// Base or Super Class


class Employee {
int salary = 60000;
}

// Inherited or Sub Class


class Engineer extends Employee {
int benefits = 10000;

JAVA Page 26
}

// Driver Class
class Gfg {
public static void main(String args[])
{
Engineer E1 = new Engineer();
System.out.println("Salary : " + E1.salar + "\nBenefits : " + E1.benefits);
}
}

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

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

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

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

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

JAVA Page 27
}
// Driver Class
public class Test {
public static void main(String[] args)
{
B obj_B = new B();
obj_B.print_A();
obj_B.print_B();

C obj_C = new C();


obj_C.print_A();
obj_C.print_C();

D obj_D = new D();


obj_D.print_A();
obj_D.print_D();
}
}

Advantages Of Inheritance in Java:


1. Code Reusability: Inheritance allows for code reuse and reduces the amount of code
that needs to be written. The subclass can reuse the properties and methods of the
superclass, reducing duplication of code.
2. Abstraction: Inheritance allows for the creation of abstract classes that define a
common interface for a group of related classes. This promotes abstraction and
encapsulation, making the code easier to maintain and extend.
3. Class Hierarchy: Inheritance allows for the creation of a class hierarchy, which can be
used to model real-world objects and their relationships.
4. Polymorphism: Inheritance allows for polymorphism, which is the ability of an object to
take on multiple forms. Subclasses can override the methods of the superclass, which allows
them to change their behavior in different ways.

1.2.7 Interfaces in Java

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.

What are Interfaces in Java?


The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not the method body. It is used to achieve abstraction
and multiple inheritances in Java using Interface. In other words, you can say that interfaces
can have abstract methods and variables. It cannot have a method body. Java Interface
also represents the IS-A relationship.

interface {
// declare constant fields
// declare methods that abstract
// by default.
}

To declare an interface, use the interface keyword. It is used to provide total abstraction. That
means all the methods in an interface are declared with an empty body and are public and all
fields are public, static, and final by default. A class that implements an interface must
implement all the methods declared in the interface. To implement the interface, use the
implements keyword.

JAVA Page 28
Uses of Interfaces in Java are mentioned below:
 It is used to achieve total abstraction.
 Since java does not support multiple inheritances in the case of class, by using an
interface it can achieve multiple inheritances.
 Any class can extend only 1 class, but can any class implement an infinite number of
interfaces.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction.

// Java program to demonstrate working of


// interface

import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.

class TestClass implements In1 {

// Implementing the capabilities of interface.

public void display(){


System.out.println("Geek");
}

// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}

Multiple Inheritance in Java Using Interface

Multiple Inheritance is an OOPs concept that can’t be implemented in Java using classes. But
we can use multiple inheritances in Java using Interface. let us check this with an example.

interface API {
// Default method
default void show()
{

// Print statement System.out.println("Default API");


}

JAVA Page 29
}

// Interface 2 // Extending the above interface

interface Interface1 extends API {


// Abstract method
void display();
}

// Interface 3 // Extending the above interface

interface Interface2 extends API {


// Abstract method
void print();
}

// Main class // Implementation class code


class TestClass implements Interface1, Interface2 {

// Overriding the abstract method from Interface1


public void display()
{
System.out.println("Display from Interface1");
}
// Overriding the abstract method from Interface2
public void print()
{
System.out.println("Print from Interface2");
}
// Main driver method
public static void main(String args[])
{
// Creating object of this class in main() method
TestClass d = new TestClass();

// Now calling the methods from both the interfaces


d.show(); // Default method from API
d.display(); // Overridden method from Interface1
d.print(); // Overridden method from Interface2
}
}

Difference Between Class and Interface

Although Class and Interface seem the same there have certain differences between Classes
and Interface. The major differences between a class and an interface are mentioned below:
Class Interface

In class, you can instantiate variables and In an interface, you can’t instantiate variables
create an object. and create an object.

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

JAVA Page 30
Class Interface

The access specifiers used with classes


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

1.2.8 Java Abstraction (Abstract Class)

Data abstraction is the process of hiding certain details and showing only essential information
to the user. Abstraction can be achieved with either abstract classes or interfaces

The abstract keyword is a non-access modifier, used for classes and methods:

 Abstract class: is a restricted class that cannot be used to create objects (to access it,
it must be inherited from another class).
 Abstract method: can only be used in an abstract class, and it does not have a body.
The body is provided by the subclass (inherited from).

Characteristics of Java abstract Keyword


In Java, the abstract keyword is used to define abstract classes and methods. Here are some
of its key characteristics:
 Abstract classes cannot be instantiated: An abstract class is a class that cannot be
instantiated directly. Instead, it is meant to be extended by other classes, which can provide
concrete implementations of its abstract methods.
 Abstract methods do not have a body: An abstract method is a method that does
not have an implementation. It is declared using the abstract keyword and ends with a
semicolon instead of a method body. Subclasses of an abstract class must provide a concrete
implementation of all abstract methods defined in the parent class.
 Abstract classes can have both abstract and concrete methods: Abstract classes
can contain both abstract and concrete methods. Concrete methods are implemented in the
abstract class itself and can be used by both the abstract class and its subclasses.
 Abstract classes can have constructors: Abstract classes can have constructors,
which are used to initialize instance variables and perform other initialization tasks. However,
because abstract classes cannot be instantiated directly, their constructors are typically called
constructors in concrete subclasses.
 Abstract classes can contain instance variables: Abstract classes can contain
instance variables, which can be used by both the abstract class and its subclasses.
Subclasses can access these variables directly, just like any other instance variables.
 Abstract classes can implement interfaces: Abstract classes can implement
interfaces, which define a set of methods that must be implemented by any class that
implements the interface. In this case, the abstract class must provide concrete
implementations of all methods defined in the interface.

abstract class gfg


{
abstract void printInfo();
}

// Child Class
class employee extends gfg {
void printInfo()
{
String name = "aakanksha";
int age = 21;

JAVA Page 31
float salary = 55552.2F;

System.out.println(name);
System.out.println(age);
System.out.println(salary);
}
}

// driver Class
class base {
// main function
public static void main(String args[])
{
// object created
gfg s = new employee();
s.printInfo();
}
}

abstract class A {
// abstract with method // it has no body
abstract void m1();

// concrete methods are still // allowed in abstract classes

void m2()
{
System.out.println("This is a concrete method.");
}
}

// concrete class B
class B extends A {

// class B must override m1() method // otherwise, compile-time exception will be thrown

void m1()
{
System.out.println("B's implementation of m1.");
}
}

// Driver class
public class AbstractDemo {
// main function
public static void main(String args[])
{
B b = new B();
b.m1();
b.m2();
}
}

JAVA Page 32
1.2.9 Difference between Abstraction and Encapsulation in Java

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. 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 data of a class is hidden from any
other class and can be accessed only through any member function of its own 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. Encapsulation can be achieved by Declaring all the variables in
the class as private and writing public methods in the class to set and get the values of
variables.
Abstraction Encapsulation

Abstraction is the process or method While encapsulation is the process or method to


of gaining the information. contain the information.

In abstraction, problems are solved at While in encapsulation, problems are solved at


the design or interface level. the implementation level.

Whereas encapsulation is a method to hide the


Abstraction is the method of hiding
data in a single entity or unit along with a method
the unwanted information.
to protect information from outside.

Whereas encapsulation can be implemented


We can implement abstraction using
using by access modifier i.e. private, protected
abstract class and interfaces.
and public.

In abstraction, implementation
While in encapsulation, the data is hidden using
complexities are hidden using
methods of getters and setters.
abstract classes and interfaces.

The objects that help to perform Whereas the objects that result in encapsulation
abstraction are encapsulated. need not be abstracted.

Abstraction provides access to Encapsulation hides data and the user can not
specific part of data. access same directly (data hiding.

Abstraction focus is on “what” should Encapsulation focus is on “How” it should be


be done. done.

1.2.10 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 it’s type.
Real-life Illustration of Polymorphism in Java: A person at the same time can have different
characteristics. 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

JAVA Page 33
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.
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.
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.

Function Overloading

Polymorphism is that in which we can perform a task in multiple forms or ways. It is applied
to the functions or methods. Polymorphism allows the object to decide which form of the
function to implement at compile-time as well as run-time.

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

class A {
int a, b, c;

public void add(int x, int y)


{
a = x;
b = y;
System.out.println("addition of a+b is:" + (a + b));
}

public void add(int x, int y, int z)


{
a = x;
b = y;
c = z;
System.out.println("addition of a+b+c is:" + (a + b + c));
}

public void print()


{
System.out.println("Class A's method is running");
}
};

JAVA Page 34
class B extends A {
public void print()
{
System.out.println("Class B's method is running");
}

// Driver Code
public static void main(String[] args)
{
A a1 = new A();

// method overloading (Compile-time polymorphism)


a1.add(6, 5);

// method overloading (Compile-time polymorphism)


a1.add(1, 2, 3);

B b1 = new B();

// Method overriding (Run-time polymorphism)


b1.print();
}
}

Dynamic Method Dispatch /Runtime Polymorphism (Function Overriding ) in Java

In Java, Overriding is a feature that allows a subclass or child class to provide a specific
implementation of a method that is already provided by one of its super-classes or parent
classes. When a method in a subclass has the same name, the same parameters or signature,
and the same return type(or sub-type) as a method in its super-class, then the method in the
subclass is said to override the method in the super-class.

// Java program to demonstrate


// method overriding in java

// Base Class
class Parent {
void show() { System.out.println("Parent's show()"); }
}

// Inherited class
class Child extends Parent {
// This method overrides show() of Parent
@Override void show()
{
System.out.println("Child's show()");
}
}

// Driver class
class Main {
public static void main(String[] args)
{
// If a Parent type reference refers to a Parent object, then Parent's show is called

Parent obj1 = new Parent();

JAVA Page 35
obj1.show();

// If a Parent type reference refers to a Child object Child's show() is called. This is called
RUN TIME POLYMORPHISM.

Parent obj2 = new Child();


obj2.show();
}
}

1.2.11 Packages In Java

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


Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Here, we will have the detailed learning of creating and using user-defined packages.
Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Packages are used for:

 Preventing naming conflicts. For example there can be two classes with name Employee
in two packages, college.staff.cse.Employee and college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
 Providing controlled access: protected and default have package level access control. A
protected member is accessible by classes in the same package and its subclasses. A
default member (without any access specifier) is accessible by classes in the same
package only.

Built-in Packages These packages consist of a large number of classes which are a part of
Java API.Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(.


2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces
(like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

User-defined packages These are the packages that are defined by the user.

JAVA Page 36
Simple example of java package

/ Name of package to be created


package data;

// Class to which the above package belongs


public class Demo {

// Member functions of the class- 'Demo'


// Method 1 - To show()
public void show()
{

// Print message
System.out.println("Hi Everyone");
}

// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}

Again, in order to generate the above-desired output first do use the commands as specified
use the following specified commands

Procedure:
1. To generate the output from the above program

Command: javac Demo.java

2. This Command Will Give Us a Class File


Command: javac -d . Demo.java

3. So This Command Will Create a New Folder Called data.


Note: In data Demo.java & Demo.class File should be present

JAVA Page 37
Example 3: Data will be tried to be accessed now from another program:

// Name of the package


import data.*;

// Class to which the package belongs


class ncj

// main driver method


public static void main(String arg[])
{

// Creating an object of Demo class


Demo d = new Demo();

// Calling the functions show() and view()


// using the object of Demo class
d.show();
d.view();
}
}

Again the following commands will be used in order to generate the output first a file will be
created ‘ncj.java’ outside the data directory.

Command: javac Demo.java

The Above Command Will Give us a class file that is non-runnable so we do need a
command further to make it an executable run file.

Command: java ncj

// To Run This File

Output: Generated on the terminal after the above command Is executed


Hi Everyone

Hello

1.2.12 JAR files in Java

A JAR (Java Archive) is a package file format typically used to aggregate many Java class
files and associated metadata and resources (text, images, etc.) into one file to distribute
application software or libraries on the Java platform.

In simple words, a JAR file is a file that contains a compressed version of .class files, audio
files, image files, or directories. We can imagine a .jar file as a zipped file(.zip) that is
created by using WinZip software. Even, WinZip software can be used to extract the
contents of a .jar . So you can use them for tasks such as lossless data compression,
archiving, decompression, and archive unpacking.

JAVA Page 38
Let us see how to create a .jar file and related commands which help us to work with .jar
files

1.1 Create a JAR file

In order to create a .jar file, we can use jar cf command in the following ways as discussed
below:
Syntax:
jar cf jarfilename inputfiles
Here, cf represents to create the file. For example , assuming our package pack is available
in C:\directory , to convert it into a jar file into the pack.jar , we can give the command as:
C:\> jar cf pack.jar pack

1. 2 View a JAR file

Now, the pack.jar file is created. In order to view a JAR file ‘.jar’ files, we can use the
command as:
Syntax:
jar tf jarfilename
Here, tf represents the table view of file contents. For example, to view the contents of our
pack.jar file, we can give the command:
C:/> jar tf pack.jar
Now, the contents of pack.jar are displayed as follows:
META-INF/
META-INF/MANIFEST.MF
pack/
pack/class1.class
pack/class2.class
..
..
Here class1, class2, etc are the classes in the package pack. The first two entries represent
that there is a manifest file created and added to pack.jar. The third entry represents the
sub-directory with the name pack and the last two represent the files name in the directory
pack.

Note: When we create .jar files, it automatically receives the default manifest file. There can
be only one manifest file in an archive, and it always has the pathname.
META-INF/MANIFEST.MF
This manifest file is useful to specify the information about other files which are packaged.

1.3 Extracting a JAR file

In order to extract the files from a .jar file, we can use the commands below listed:
jar xf jarfilename
Here, xf represents extract files from the jar files. For example, to extract the contents of our
pack.jar file, we can write:
C:\> jar xf pack.jar
This will create the following directories in C:\
META-INF
In this directory, we can see class1.class and class2.class.
pack

1.5 Running a JAR file


In order to run an application packaged as a JAR file (requires the Main-class manifest
header), the following command can be used as listed:
Syntax:
C:\>java -jar pack.jar

JAVA Page 39

You might also like