Unit 1 Java
Unit 1 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
.
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
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.
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.
Program Output:
Hello Java
Here are the most important points to note about the Java programs:
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.
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.
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.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'
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.
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
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.
class Simple
{
public static void main(String[] args)
{
int a=10;int b=10;
int c=a+b;
System.out.println(c);
}}
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
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.
JAVA Page 11
Java programming language provides the following types of loop to handle looping
requirements. Click the following links to check their detail.
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.
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.
JAVA Page 12
Example
public class Test {
for(int x : numbers ) {
System.out.print( x );
System.out.print(",");
}
System.out.print("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};
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 {
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.
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 −
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 −
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 −
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 −
JAVA Page 17
Module 2: Java - Object and Classes
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.
JAVA Page 18
Components of Java Classes
Java Objects
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;
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();
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
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:
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();
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.
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.
primarily there are two types of constructors in Java are mentioned below:
Default Constructor
Parameterized Constructor
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
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
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");
}
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.
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");
}
}
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;
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 {
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.
import java.io.*;
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);
}
}
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();
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.
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.
import java.io.*;
// A simple interface
interface In1 {
// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(a);
}
}
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()
{
JAVA Page 29
}
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
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).
// 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();
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
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.
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?
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;
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();
B b1 = new B();
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.
// 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
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.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
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:
User-defined packages These are the packages that are defined by the user.
JAVA Page 36
Simple example of java package
// 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
JAVA Page 37
Example 3: Data will be tried to be accessed now from another program:
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.
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.
Hello
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
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
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.
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
JAVA Page 39