0% found this document useful (0 votes)
9 views327 pages

Object Oriented 2020

Uploaded by

katikalapavan08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views327 pages

Object Oriented 2020

Uploaded by

katikalapavan08
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 327

Object Oriented Programming

Object Oriented Programming


What is object oriented programming?
1)Object-Oriented Programming is a programming
pattern that makes use of objects and their interactions to
design and implement applications
2)Objects are entities that serve as the basic building
blocks of an object-oriented application
3)An object is a self-contained entity with attributes and
behaviors

2
Object Oriented Programming

3
Object Oriented Programming
What is an Object?
1)An entity which does exist, has state and behavior is known as an
object e.g. chair, bike, marker, pen, table, car etc.
2)If something does not really exist, then it is not an object e.g. our
thoughts, imagination, plans, ideas etc.,
3)According to System existence means contains memory. So a
software object represent a memory.
4)Software objects also have a state and a behavior. A software
object's state is stored in variables and behavior is shown via
methods. So an object contains variables and methods

4
Object Oriented Programming
What is a Class?
1)It is possible that some objects may have similar properties and
actions. Such objects belongs to same category called a ‘class’
2)It is only an logical component and not the physical entity e.g. if
you had a class called “Expensive Cars” it could have objects like
Mercedes, BMW, Toyota, etc.
3) Its properties(data) can be price or speed of these cars.
4)While the methods may be performed with these cars are driving,
reverse, braking etc.

5
Object Oriented Programming
Class and Objects

6
Object Oriented Programming
What is an abstraction in Java?
In object oriented programming abstraction is a process of
providing functionality to the users by hiding its implementation
details from them
In other words, the user will have just the knowledge of
what an entity is doing instead of its implementation

7
Object Oriented Programming
Real life example of Abstraction is ATM Machine; All are
performing operations on the ATM machine like cash
withdrawal, money transfer, retrieve mini-statement…etc.
but we can't know internal details about ATM.

8
Object Oriented Programming
Advantages of Abstraction

9
Object Oriented Programming
How to Achieve Abstraction in Java?
In Java, we can achieve Data Abstraction using Abstract
class and Interface
Interface allow 100% abstraction(complete abstraction).
Interface allow you to abstract the implementation
completely
Abstract class allow 0 to 100% abstraction (partial to
complete abstraction)because abstract class can contain
concrete methods that have the implementation which
results in a partial abstraction

10
Object Oriented Programming
What is an Encapsulation?
1)We can define it as Encapsulation is the wrapping up of data and
functions (methods that operate on the data) into a single unit
(called class).
2)There is a prohibition for direct access to the data. Functions
(that combine with the data) are the only way to access data.
These functions are the member functions or methods in Java. It
basically creates a shield due to which the code or data cannot be
accessed outside the shield.
3)In Java class bind the data with its associated method so class is
an example of encapsulation

11
Object Oriented Programming

12
Object Oriented Programming
Achieving Encapsulation in Java
In order to achieve encapsulation in Java, we have to
1)declare the variables of a class as private, so that they cannot be
accessed directly from outside the class.
2)provide setter and getter methods that are declared as public, to
view and change the values of the variables.

13
Object Oriented Programming
Inheritance in Java
1)The process by which one class acquires the properties(data
members) and functionalities(methods) of another class is
called inheritance.
2)In the inheritance the class which is give data members and
methods is known as base or super or parent class.
3)The class which is taking the data members and methods is
known as sub or derived or child class

14
Object Oriented Programming

15
Object Oriented Programming
Polymorphism in Java
Polymorphism is the ability for a data or message to be processed
in more than one form. It is a concept by which a single
operation can be performed in multiple different ways.
For example, a security guard outside an organization behaves
differently with different people entering the organization. He
acts in a different way when the Boss comes and, in another way
when the employees come. When the customers enter, the guard
will respond differently. So here, the behavior of the guard is in
various forms, which depends on the member who is coming.

16
Object Oriented Programming

17
Object Oriented Programming
We can define polymorphism in the context of Object-Oriented
Programming as follows:
“The virtue (good future) by which the same action can be
performed by objects of different classes and each object
responds in a different way depending on its class is called
Polymorphism”.

18
Object Oriented Programming

19
Creation of Class and it’s Data
members and an Object
Object Oriented Programming
1) Anything that exists as a part of the Java program has to be
present as a part of a class, whether it is a variable or a method
or any other code fragments. The reason is that Java is a pure
Object Oriented language, in which all the functionalities
revolve around the classes and objects.
2) So, without a class, there can be no objects and without objects,
no computation can take place in Java. Thus, a class is the basis
of all computations in Java.
3) A class allows the programmer to define all the variables and
methods that internally define the state/properties and behavior
of an object

21
Object Oriented Programming
The syntax for declaring classes:
<modifier> class <ClassName>{
//Class body containing variables and methods
}
Variables & methods are called members of the class.
Variables may be the instance variables or static/class variables.
Similarly, methods may be instance methods or static/class methods.
Example
public class Student{
String name;
int age;
void display(){
//method body;
}
}
Note:
For a class valid modifiers are public, default, abstract and final
22
Object Oriented Programming
Modifiers In Java
In Java, to give access limitation, restriction, and permission to the class,
attributes, methods, and constructor we use modifiers.
Types Of Modifiers In Java
1)Access Modifier
This type of modifier is used to control the access level of the class,
attributes, methods, and constructor.
2)Non-Access Modifier
This type of modifiers used to restrict the further use of a class, attributes,
methods, and constructor and there is another use also other than
controlling access.

23
Object Oriented Programming

24
Object Oriented Programming
Java public access modifier
1)When applied to a class, the class is accessible from any classes
regardless of packages. This is the least restrictive access
modifier which means the widest range of accessibility, or
visibility.
2)However, if we try to access the public class in another package,
then the public class must be imported

25
Object Oriented Programming
package pack1;
public class Student {
public void name() { // Here, method has been defined with public
access modifier.
System.out.println(" My roll no. is 12");
}
}
package pack2;
import pack1.Student;//mandatory
class College{
public static void main(String args[]) {
// Creating the object of class Student from pack2.
Student obj = new Student();
obj.name();
}
} 26
Object Oriented Programming
Java default access modifier
1)This access modifier is special because it doesn’t have an
associated keyword. When no explicit access modifier is
specified, the types or members have default accessibility. It is
more restrictive than the protected modifier.
2)When a class has default accessibility, it is accessible to only
classes in the same package.

27
Object Oriented Programming
package animal;
class Wolf {//default access, because no explicit access modifier keyword
public void play() {
}
}
package human;
import animal.Wolf;
public class Person {
public void hunt() {
Wolf wolf = new Wolf(); // COMPILE ERROR
}
}
Here, because the Wolf class has default accessibility, the Person class (in
different package) cannot create new instance of it. The compiler
issues an error: cannot find symbol.
28
Object Oriented Programming
class with final modifier
The class with final non-access modifiers can't be inherent by
another class means that we can't access the properties and method
of final class in another class by doing inheritance also.
final class Test1{
//data members
}
public class Test2 extends Test1 {

}
above code generates compile time error, because final class can't
inherit by another class.
29
Object Oriented Programming
calss with abstract modifiers
The class with abstract non-access modifiers can't create their own object
in the same class so to access the properties and method we have to
inherit this class and then we can use properties and methods by creating
an object of the class which inherits the abstract class.
abstract class Demo{
//data members of a class
}
public class DemoTest{
public static void main(String[] args) {
Demo obj = new Demo();//Compile time error
}
}

30
Object Oriented Programming
Variables of a class
A variable in Java is a kind of container that contains the value during program
execution. Variable is a basic unit of storage in a program that represents
reserved storage locations, whose values can be manipulated during the
execution of a program.
In java class the following types of variables are declared

31
Object Oriented Programming
Instance variables
1)Variables defined within a class are called instance variables because
each instance of the class (that is, each object of the class) contains its
own copy of these variables. Thus, the data for one object is separate and
unique from the data for another.
Example,
class ClassName {
data_type instance-variable1 ;
data_type instance-variable2
}
2)Instance variables are created when an object is created with the use of
the keyword 'new' keyword and destroyed when the object is destroyed.
3)Instance variables hold values that must be referenced by more than
one method , constructor or block.
4)The instance variables are visible for all methods, constructors, and
block in the class.
32
Object Oriented Programming
5) 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.
6) Instance variables have default values. For numbers, the default value
is 0, for Booleans it is false, and for object references it is null.
7) Values can be assigned during the declaration or within the
constructor.
8) Instance variables can be accessed directly by calling the variable
name inside the method.
9) However, within static methods (when instance variables are given
accessibility), they should be called using the fully qualified name.
ObjectReference.VariableName.

33
Object Oriented Programming
Static variables
1)Class variables also known as static variables are declared with the
static keyword in a class, but outside a method, constructor or a block.
2)There would only be one copy of each class , regardless of how many
objects are created from it. Static variables store values for the variables
in a common memory location. Because of this common location, if one
object changes the value of a static variable, all objects of the same class
are affected.
Example of static variable
class ClassName {
access_specifier static data_type static_variable1;
access_specifier static data_type static_variable2;
}
3)Static variables are created when the program starts and destroyed
when the program stops.
34
Object Oriented Programming
4) Visibility is similar to instance variables. However, most static
variables are declared public since they must be available for users of
the class.
5) Default values are same as instance variables. Values can be assigned
during the declaration or within the constructor. Additionally,
values can be assigned in special static initializer blocks.
6) Static variables can be accessed by calling the class name
ClassName.VariableName.
7) 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.

35
Object Oriented Programming
Static variable memory allocation

36
Object Oriented Programming
Local Variable
1)A variable which is declared inside the methods, constructors, or blocks is
called local variable.
2)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.
3)Access modifiers cannot be used for local variables.
Example of local variables,
class ClassName {
data_type instance_variable1;
access_specifier static data_type static_variable ;
ClassName(data_type local_variable){
// // body of constructor
}
data_type methodname1(data_type local_variable1) {
// body of method
}
}

37
Object Oriented Programming
4) Local variables are visible only within the declared method,
constructor, or block.
5) Local variables are implemented at stack level internally.
6) 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.

38
Object Oriented Programming
Difference between instance variable and local variables

39
Object Oriented Programming
Difference between static and instance variables

40
Object Oriented Programming
Object Declaration in Java
The process of defining the variable along with its data type and name is called
the declaration state of an object. In other words, it is also called a declaration of
variable. For example,
class College{
// Declaration of Instance variables.
String name;
String city;
}
Object Initialization in Java
The process of assigning the value of the variable is called initialization state of
an object. In other words, Initialization is the process of storing data into an
object.
class College {
// Initialize the value of variables.
String name = "PIET";
String city = "Nagpur";
} 41
Object Oriented Programming
How to Initialize State of Object in Java?
There are five ways by which we can initialize the state of an object. In
other words, we can initialize the value of variables in Java by using five
ways. They are as follows:
1)During the declaration
2)By using a reference variable
3)By using a method.
4)By using constructor
5)By using setter method

42
Object Oriented Programming
During the declaration
1)In this mechanism, variable are initialized at declaration time only
2)But the problem in this way of initialization is that all objects are
initialized with same data
3)This why of initialization is suitable for declaring constants. The reason
is that constants value will not change even though we create several
objects
For example,
class Person{
private String name=“Raja”;
private int age=30;
-------------------;
--------------------;
}

43
Object Oriented Programming
Source file declaration rules
1)There can be only one public class per source code file(.java file)
2)Comments can be appear at the beginning or end of any line in the
source code file; they are independent of any of the positioning rules
discussed here
3)If there is a public class in a file the name of the file must match the
name of the public class.
For example,
public class Dog{ }
must be in a source code file named Dog.java
4)If the class is part of the package, the package statement must be the
first line in the source code file, before any import statement that may be
present
5)A source code file can have more than one non public class
6)Files with no public class can have a name that does not match any of
the class in a file
44
Object Oriented Programming
7) If there are import statements, they must go between the package
statement and the class declaration. If there isn’t package statement,
then the import statement(s) must be the first line(s) in the source
code file. If there are no package or import statements, the class
declaration must be the first line in the source code file
8) Import and package statements apply to all classes within a source
code file

45
Object Oriented Programming
By using a reference variable
In this mechanism variables are initialized by using reference of an
object.
For example,
class Person{
private String name;
private int age;
---------------
}
public class PersonReference{
public static void main(String[]args){
Person ram=new Person();
ram.name=“Ram”;//reference assign the value
ram.age=30;//reference assign the value
}
} 46
Object Oriented Programming
What is Variable Shadowing?
When a local variable has the same name as one of the instance variable, the
local variable shadows the instance variable inside the method block.
public class Person{
String name = "John";
int age = 21;
public void show(){
String name = "Roger";//having same name as instance variable
int age = 30;
System.out.println("Name: "+ name);
System.out.println("Age: "+ age);
}
public static void main(String[] args){
Person obj = new Person();
obj.show();
}
}
47
Object Oriented Programming
Why use this keyword in java ?
1)Whenever the formal parameter (variables declared with in a method or
constructor) and data members of the class(instance variables) are similar
then jvm get ambiguity (no clarity between formal parameter and
member of the class).To differentiate between formal parameter and data
member of the class, the data member of the class must be preceded by
"this".
2)this can be used to invoke current class constructor.
3)It can be used to invoke current class method (implicitly)

48
Object Oriented Programming
By using a method arguments
In this mechanism instance variable are initialized by method arguments
class Person {
String name;
int age;
//method to initialize the instance variables
void talk(String name, int age){
this.name = name;
this.age= age;
}
}
public class PersonTest{
public static void main(String[] args){
Person ram = new Person();
ram.talk(“Ram”,30);
}
}
49
Object Oriented Programming
Constructor in Java
Constructor in java is a special type of method that is used to initialize the
object.
Java constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object that is why it is known as
constructor.

50
Object Oriented Programming
Rules need to follow when writing the constructors in java.
1)Name of the constructor must be same as that of a class name. If you
give another name it will give compile time error. If you give another
name, it is neither a method because of no return type, nor constructor
because name is different from class name.
class A{
A(){
// Constructor of Class A
}
A1(){
// Compile time error, It is neither a constructor nor a method
}
}
51
Object Oriented Programming
2) Constructors must not have a return type. If you keep return type for
the constructor, it will be treated as another method. But compiler
gives a warning saying that this method has a constructor name. That
means, it is legal to have method name same as constructor name or
same as class name but it is not recommended.
class A{
A(){
// Constructor of Class A, not having any return type.
}
void A(){
// constructor having a return type, It will be treated as method but
with a warning.
}
}

52
Object Oriented Programming
3) Every class should have at least one constructor. If you don’t write
constructor for your class, compiler will give default constructor.
Default constructor is always public and it has no arguments

53
Object Oriented Programming
4) Constructor can be declared as private. If you declare constructor as
private, you can’t use it outside that class.
class A{
private A()
{
// Private Constructor
}
}
class MainClass{
public static void main(String[] args){
//You can't use private constructor ouside the class like this
// A a1 = new A();
}
}

54
Object Oriented Programming
5) One class can have more than one constructors. It is called
Constructor Overloading. Through constructor overloading, you can
have multiple ways to create objects.
class A{
A(){
// First Constructor
}
A(int i){
// Second Constructor
}
}
you can create the objects to the above class in three ways like below,
class MainClass{
public static void main(String[] args){
A a1 = new A(); //Using First Constructor
A a2 = new A(10); // Using Second Constructor
}
55
Object Oriented Programming
6) Duplicate Constructors not allowed. If you keep duplicate
constructors, you will get compile time error.
class A{
A(int i){
// Duplicate Constructor
}
A(int i){
// Duplicate Constructor
}
}

56
Object Oriented Programming
7) Only public, protected and private keywords are allowed before a
constructor name. If you keep any other keyword before a constructor
name, it gives compile time error.
class A{
final A(){
//Constructor can not be final
}
static A(){
//Constructor can not be static
}
}

57
Object Oriented Programming
8) First statement in a constructor must be either super() or this().
If you put any other statements you will get compile time error.
If you don’t include these statements, by default compiler will
keep super() calling statement. super() – It is a calling statement
to default constructor of super class.this()- it is a calling
statement to constructor of the same class.

58
Object Oriented Programming
For example,
class A{
A(){
//By Default, Compile will keep super() calling statement here.
System.out.println("First Constructor");
}
A(int i, int j){
//Compiler will not keep any statement here
this();
System.out.println("Third Constructor");
}
A(int i, int j, int k){
System.out.println("Fourth Constructor");
// super(); It will give error if you keep super() here
}
}

59
Object Oriented Programming
9) Recursive constructor calling is not allowed.
class A{
A(){
this();
// It gives compile time error
}
}

60
Object Oriented Programming
10) No Cylic calling of constructors.
class A{
A(){
this(10);
// It gives compile time error
}
A(int i){
this();
// It gives compile time error
}
}

61
Object Oriented Programming
Types of Constructors
There are three types of constructors: Default, No-arg constructor and
Parameterized.

62
Object Oriented Programming
Default constructor
If you do not implement any constructor in your class, Java compiler
inserts a default constructor into your code on your behalf. This
constructor is known as default constructor. This constructor initialize the
object properties with default values

63
Object Oriented Programming
no-arg constructor
Constructor with no arguments is known as no-arg constructor. The signature is
same as default constructor, however body can have some code unlike default
constructor where the body of the constructor is empty.
public class Person {
String name;
int age;
// Declare a default constructor.
Person(){
// Initialization of values of Instance variables.
name = "Vivek";
age = 27;
}
}
Whenever we want to place same values in multiple objects of same type of class
then we must use the concept of no-arg constructor

64
Object Oriented Programming
Parameterized constructor
Constructor with arguments(or you can say parameters) is known as
Parameterized constructor.
public class Person {
String name;
int age;
// Parameterized default constructor.
Person(String name,int age){
//this keyword required to avoid variable shadowing
this.name = name;
this.age =age;
}
}
Parameterized constructor is useful to initialize each object with different values

65
Object Oriented Programming
Constructor Overloading
1)Constructor overloading means to define multiple constructors but with
different signatures.
2)The Java compiler differentiates these constructors based on the
number of the parameter list and their types.
3)Constructor overloading allows initializing objects with different types
of data.

66
Object Oriented Programming
Constructor Overloading

67
Object Oriented Programming
Constructor Chaining
1)Constructor chaining in Java is a technique of calling one constructor
from another constructor using 'this' or 'super' keyword.
2)The keyword 'this' is used to call a constructor from another constructor
within the same class.
3)The keyword 'super' is used to call the parent (super) class constructor
from child (subclass) class constructor. It occurs through inheritance.
Why do we need constructor chaining ?
This process is used when we want to perform multiple tasks in a single
constructor rather than creating a code for each task in a single
constructor we create a separate constructor for each task and make their
chain which makes the program more readable.

68
Object Oriented Programming
Constructor changing

69
Object Oriented Programming
Java Copy Constructor
A Copy Constructor in Java is a special type of constructor that is used to
create a new object using the existing object of a class that we have
created previously. In other words, copy constructor creates a new object
by initializing the object with the instance of the same class.
Java does not implicitly provide the facility of a Copy constructor as in
C++ language. But, we can define it by copying the values of one object
to another object.

70
Object Oriented Programming
There are two statements given below.
Student s1 = new Student();
Student s2 = new Student(s1);
If we write s2 = s1 then it means that s2 is an object reference variable
which is created the same as the object reference variable s1 and both s1
and s2 are pointing to the same object. No content is copied.

But when we create Student s2 = new Student(s1); it means that an object


reference variable s2 is created and it is pointing to a Student object
created through the new operator which will call to a copy constructor to
copy contents from the first object.

71
Object Oriented Programming
Methods in Java
In Java, the programs (executable instructions) are specified through
methods or functions. A method is defined as a sequence of some
declaration and execution statements. These statements gather together to
perform a specific task.
The general form of a function/method is given below
[access-specifier] [modifier] return-type function-name (parameter list)
{
body of the function/method;
}

72
Object Oriented Programming
Methods in Java

73
Object oriented programming
1) The method modifier defines the access type of a method but it
is optional to use. It may be declared as static, final, abstract,
synchronized, or one of the access specifiers private, default,
protected, and public.
2) The return type defines the type of data that comes back from
the method after calling it.
3) The parameter list is a comma-separated list of zero or more
parameter declaration.
Note
If there is more than one parameter, they are separated by commas.
If there are no parameters, you include an empty pair of
parentheses ().

74
Object oriented programming
4) The method body is a block-statement which contain
statements as well as the declaration of the local
variables and local classes. The method body may
also contain return statements.
Note
If the return type is void, the method can perform a task
without returning any value. Such a method is called
void method. There will be no return statement inside
the method body.
If the return type is non-void but a data-type like int,
float, double, etc, the method will return a value. It
will not be possible for execution to reach the end of
the method body without executing a return statement. 75
Object oriented programming
Method Signature in Java
The method name with the parameter list (number of parameters,
type of parameters, and order of parameters ) is called method
signature in java.
Examples of methods signature are
add(int a, int b)
m1(String name)
sub(): No parameter.
Key points about Method Signature
1)The return type and exceptions are not part of the method
signature.
2)The method name should be functionality name related to logic.
3)The exceptions may be thrown by the methods. In this case, you
can specify the exceptions.
76
Object oriented programming
Some examples of different types of method declaration
in java.
public void add(int a, int b);
Here, add is the method name. It will execute whenever we will
pass input values of a and b.
Once the functionality is completed, void represents don’t return
any value. The public is access modifiers which represent that this
method can be accessed from anywhere.
private int m2();
m2 is method name with no argument. Once the functionality is
completed, it must return an integer value. The private access
modifier represents that it can be accessed only within the class.

77
Object oriented programming
Types of methods in Java
1)Predefined methods
2)User-defined methods (Programmer-defined methods)

78
Object oriented programming
Predefined methods in Java
Predefined methods are those methods that are already defined in
the Java API to use in an application. Java Programming language
contains predefined classes that are organized in different
predefined packages. Within these predefined classes, there are
located predefined methods.
For example:
print() is a predefined method present in the package
java.io.PrintSteam.
sqrt() is a method of Math class which is present in package
java.lang. It calculates the square root of a number.
max() predefined method returns the greater of two values.
In fact, Java has over 160 predefined packages that contain more
than 3000 predefined classes.
79
Object oriented programming
User-defined methods in Java
User-defined methods are those methods which are
defined by the programmer inside a class to perform
special task or function in an application.
Types of user-defined methods
1)Instance method
2)Static method

80
Object oriented programming
Instance method
An instance method is used to implement behaviors of each
object/instance of the class. Therefore, they are linked with an
object. An instance method is also known as non-static method.
So, without an object of the class, the methods cannot exist to
perform their desired behaviors or task. It is allocated in the heap
memory during the object creation.
Example of an instance method declaration
void m1() {
// This area is called an instanced area/ Non-static area.
// logic here.
}

81
Object oriented programming
Static method
When you declare any method with a static modifier, it is called
static method. A static method is linked with class. Therefore, it is
also known as a class method. It is used to implement the behavior
of the class itself. Static methods load into the memory during class
loading and before object creation.
Example of a static method declaration
static void m2(){
// This area is called a static area.
// logic here.
}
Note
1)An instance method can refer to static variables (class variables)
as well as instance variables of the class.
2)A static method can refer to only static variables. 82
Object oriented programming
How to Call Method in Java
Executing code inside the body of a method is called calling a
method (or invoking a method).
Calling Instance method in Java
There are two steps to call an instance method in java.
1)First, create an object of a class before calling an instance method
of that class.
2)Second, call the method with a reference variable using the dot
operator.
Syntax
instance_reference.instance_method_name(actual parameters);
For example
Test t = new Test();
t.msg();
83
Object oriented programming
Calling Static method in Java
To call a static method, we use dot operator with the class
name.
For example:
The following code calls m1() static method of Test class.
Test.m1();

Note
1)Instance method uses dynamic binding (late binding).
2)Class method uses static binding (early binding).
84
Object oriented programming
Method calling rules
1)If you call instance members (variables or methods) from
instance area within an instance area (i.e, same area), you don’t
need to use object reference variable for calling instance variables
or methods. You call it directly.
2)If you call instance variables or methods from the static area (i.e,
different area), you cannot call directly them. You will have to use
object reference variables for calling them.
3)If you call static members (variables or methods) from the static
area or instance area, we don’t need to use the class name for
calling the static members. You can invoke directly.
4)When you want to call static members from the outside the class,
static members can be accessed by using the class name only.

85
Object oriented programming

86
Object oriented programming
How to call Instance method in Java from main
To call an instance method from the main method is very
simple. Just create an object of the class and call the
method using the reference variable.
How to call Static method from main in Java
Using the class name, you can directly call a static
method from the main method.

87
Object oriented programming
Method calling process

88
Object oriented programming
Arguments or Actual Parameters in Java
Whenever any particular method is called during the execution of
the program, there are some values that are passed to call that
particular method. These values are called arguments, also called
actual parameter.
The passed argument values replace those parameters which have
been used during method definition and the method is then
executed with these values.
The type of argument values passed must be matched with the type
specified for the corresponding parameter in the definition of
method.
For example:
add(5,7);
The values 5 and 7 are the arguments with which a method will be
called. 89
Object oriented programming
Parameter or Formal parameter in Java
In Java, a parameter is a variable name with type that is declared
within the method signature. The list of parameters is enclosed in
parenthesis.
Each parameter consists of two parts: type name, and variable name.
A type name followed by a variable name defines the type of value
that can be passed to a method when it is called. It is also often called
formal parameter.
Parameters declared in method signature are always local variables
that receive values when the method is called.
For example:
public int add(int a, int b){
return (a+b);
}
The method add() has two parameters, named a and b with data type integer. It adds
the values passed in the parameters and returns the result to the method caller. 90
Object oriented programming
Call by Value and Call by Reference in Java
In Java, all argument values are passed to a method using
only call by value (pass by value) mechanism. There is no
call by reference (pass by reference) mechanism in Java.

91
Object oriented programming
Call by Value (Pass by Value) in Java
1)“Call by value” in Java means that argument’s value is copied and is passed to
the parameter list of a method. That is, when we call a method with passing
argument values to the parameter list, these argument values are copied into the
small portion of memory and a copy of each value is passed to the parameters of
the called method.
2)When these values are used inside the method either for “read or write
operations”, we are actually using the copy of these values, not the original
argument values which are unaffected by the operation inside the method.
3)That is, the values of the parameters can be modified only inside the scope of
the method but such modification inside the method doesn’t affect the original
passing argument.
4)When the method returns, the parameters are gone and any changes to them are
lost. This whole mechanism is called call by value or pass by value.

92
Object oriented programming
Call by Value Mechanism

93
Object oriented programming
Call by Reference (Pass by Reference) in Java
1)In Java “Call by Reference” means passing a reference (i.e.
address) of the object by value to a method.
2)Thus, when we pass a variable of class type as an argument to a
method, actually, a copy of a reference (address) to an object is
passed by value to the method, not a copy of the object itself
because Java does not copy the object into the memory.
3)Actually, it copies reference of the object into the memory and
passes the copy to the parameters of the called method. If we
change the reference of the object then the original reference does
not get changed because this reference is not original. It’s a copy.

94
Object Oriented Programming

95
Object Oriented Programming
Static Content Of a Class
In Java using a static keyword, we can have a static method, static class,
static block, static variable.
This keyword is mainly used for the management of memory.
We can use static keyword with methods, variables means that they
belongs to a class rather than the instance of the class.
Static can be
1)Block
2)Variable (also known as a class variable)
3)Method (also known as a class method)
4)Class (Inner class only)

96
Object Oriented Programming
Static Variable in Java
Any variable which is declared using ‘static’ keyword is a static variable.
Memory allocation for a static variable happens only once in the class
area when the class is loaded in the memory. It is also known as a class
variable. It is common to all the objects of the class.

97
Object Oriented Programming
Static Methods in Java
1)These are declared with the keyword “static” when defining a method
2)This method belongs to the class and not to the object.
3)It can access only static data. It can not access instance variables.
4)A static method can call only static methods, non-static methods are not
called by a static method.
5)This method is can be accessed by the class name it doesn’t need any
object.

98
Object Oriented Programming
Static Block in Java
1)A static block is a block of code which contains code that executes at
class loading time.
2)A static keyword is prefixed before the start of the block.
3)All static variables can be accessed freely
4)Any non-static fields can only be accessed through object reference,
thus only after object construction.
5)multiple static blocks would execute in the order they are defined in the
class.
6)All static blocks executes only once per classloader
A typical static block looks like
static{
// code for static block
} 99
Object Oriented Programming
Non-static block
1)A non-static block executes when the object is created, before the
constructor
2)There is no keyword prefix to make a block non-static block, unlike
static blocks.
3)Incase of multiple non-static blocks , the block executes the order in
which it is defined in the class.
4)All static and non-static fields can be access freely.
5)All non-static block executes every time an object of the containing
class is created.
A typical non-static block looks like below
{
// non static block
} 100
Java bean Class
Object Oriented Programming
What is Java Bean?
According to Java, it is a reusable software component. A bean encapsulates
many objects into one object so that we can access this object from multiple
places. Moreover, it provides easy maintenance.
To make a java class as a JavaBean Class the following rules to be followed
1)The class must be public
2)The class must contains a public default constructor
3)All properties of the class should be private
4)Each property should contain a public setter(should be prefixed with set) and
getter(should be prefixed with get) method
For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
5)The class can optionally implement serializable interface

102
Object Oriented Programming
Getter method in Java
A method which is used to retrieve/get the value of a variable or return
the value of the private member variable is called getter method in Java.
This method is also known as accessor method. For every private
variable, you should create a getter method.
Setter method in Java
A method which is used for updating or setting the value of a variable is
called setter method in Java. This method is also known as mutator
method. By using the setter method, you can modify the value of a
variable. Just like with the getter method, you should create a setter
method for every variable in the class.

103
Object Oriented Programming
Naming convention of Getter and Setter method in Java
getXxx() and setXxx() where Xxx is the name of the variable.
For example:
private int number;
then appropriate getter and setter will be like this:
public getNumber() { }
public void setNumber(int number) { }
Similarly,
If the variable is a type of boolean then
private boolean rich;
public getRich() { }
public setRich() { }

104
Object Oriented Programming
Note
1)If you define only the getter method, it can be made read-only.
2)If you define only the setter method, it can be made write-only.
3)If you define both getter and setter methods, it can be made read-write.

105
Object Oriented Programming
POJO(Plain Old Java Object)
To make a java class as a POJO then that class shouldn’t extend any
predefined base class and shouldn’t implement any predefined interface
except serilizable interface
Every JavaBean is a POJO but every POJO is not a JavaBean

106
Encapsulation In Java
Object Oriented Programming
What is an Encapsulation?
Encapsulation is the process of combining data and code into a single unit
(object / class). In OOP, every object is associated with its data and code.
In programming, data is defined as variables and code is defined as
methods. The java programming language uses the class concept to
implement encapsulation.

108
Object Oriented Programming
Achieving Encapsulation in Java
1)declare the variables of a class as private, so that they cannot be
accessed directly from outside the class.
2)provide setter and getter methods that are declared as public, to
view and change the values of the variables.
Note
If you want to read data items in an object, you call the member
function in the object. It will read the data item from the function
and return the value to you. You can’t access the data directly using
the object. The data is hidden, so it is kept protected and safe from
accidental alteration.

109
Object Oriented Programming
Advantages of Encapsulation
Data hiding - If the field is declared private in the class then it
cannot be accessed by anyone from outside the class and hides the
field within the class. Therefore, it is also called data hiding.
Getter and Setter Methods – We can access private members-only
within the same class. A class that is present outside this class can
not access the private data members. If you need to access these
private variables, you have to use public “setter” and “getter”
methods.

110
Object Oriented Programming
Flexibility and Maintainability – With the help of encapsulation, we can
make the fields of the class as write-only (If we only define the setter
methods in the class) or read-only (If we only define the getter methods
in the class) according to our requirements. It enhances the flexibility and
maintainability of the code.
Code Reusability – It allows the programmer or a user to effectively use
the existing code again and again.
Total Control – A class can have total control over what is stored in its
variables and fields.
Ease of Testing – With encapsulation, the testing becomes very easy. So,
it is much better for Unit testing.

111
Object Oriented Programming
What would happen if we do not use Encapsulation?
If we don’t use encapsulation, the fields will not be private and could be
accessed by anyone from outside the class.
class Student {
String id; // Here, No encapsulation is used. Since the field is not private.
}
public class EncapsulationTest {
public static void main(String[]args) {
Student st = new Student();
st.id="2"; // As the field is not private. So, it can be accessed by anyone
from outside the class.
}
}
112
Object Oriented Programming
Data Hiding in Java
An outside person cannot access our internal data directly or our
internal data should not go out directly. This oops feature is called
data hiding n Java.
How to achieve Data hiding programmatically?
By declaring data members (variables) as private, we can achieve
or implement data hiding. If the variables are declared as private in
the class, nobody can access them from outside the class. The
biggest advantage of data hiding is we can achieve security.

113
Object Oriented Programming
Note
1)It is highly recommended to declare data members as private in
the class.
2)A combination of data hiding and abstraction is nothing but
encapsulation.
Encapsulation = Data Hiding + Abstraction
3)If any component follows data hiding and abstraction, it is called
an encapsulated component.
4)If each variable is declared as private in the class, it is called
tightly encapsulated class in Java.

114
Association or
Relationship between the
classes In Java
Association In Java
What is an Association?
Association is a connection between two separate classes that build
up through their references. The association builds a relationship
between the classes and tells how much a class knows about another
class. This relationship can be unidirectional or bi-directional. In
Java, the association can have one-to-one, one-to-many, and many-to-
many relationships.
For example,
One to One: A person can have only one voter id card
One to many: A Bank can have many Employees
Many to one: A Country can have many states
Many to Many: A Bank can have multiple customers and a customer
can have multiple bank accounts.

116
Object Oriented Programming
Association

117
Object Oriented Programming
Composition and Aggregation are the two forms of association.

118
Object Oriented Programming
Aggregation or has-a relationship
Aggregation is a relation between two classes which setup through entity
reference, it can be described as has-a and part or whole relationship.
An aggregation is a form of Association, which is a one-way relationship
or a unidirectional association.
For example, customers can have orders but the reverse is not possible,
hence unidirectional in nature.
class Customer{
int cid;
String cname;
Order ordering;
}

119
Object Oriented Programming
Composition
Composition relation is a restricted form of Aggregation in which two
classes (or entities) are highly dependent on each other, the composed
object cannot exist without the other entity. The composition can be
described as a part-of relationship.
Example of Composition( Part – Of)
A car has an engine. Composition makes strong relationship between the
objects. It means that if we destroy the owner object, its members also
will be destroyed with it. For example, if the Car is destroyed the engine
is destroyed as well.

120
Inheritance In Java
Object Oriented Programming
What is an Inheritance?
1) The process by which one class acquires the properties(data members) and
functionalities(methods) of another class is called inheritance.
2) In the inheritance the class which is give data members and methods is known
as base or super or parent class.
3) The class which is taking the data members and methods is known as sub or
derived or child class
Note
In Java, one class can inherit properties of another class and can have its own
properties too. That is, subclass/child-class can inherit properties of its
superclass/parent-class, as well as it can contain its own properties.

122
Object Oriented Programming
Inheritance in Java

123
Object Oriented Programming
Advantages of Inheritance
Code reusability
Once the code is written in a superclass (parent class) there is no need to
write it again in a subclass (child class) because a subclass automatically
inherits the code written in a superclass.
To inherit a superclass into a subclass, we just need to use extends
keyword.
Code enhancement
The subclass can use code inherited from superclass as well as it can have
its own code too.
It’s like that a son can use the Car of a father as well as he has the
freedom to buy his own Car too.
Run time polymorphism can be achieved
Runtime polymorphism can be achieved with the use of method
overriding in inheritance.
124
Object Oriented Programming
Syntax for inheritance
class Superclass{
// fields and methods of superclass
}
class Subclass extends Superclass{
// fields and methods of subclass
}
The extends keyword indicates that the subclass (Child class) is inheriting
properties of superclass (Parent class).

125
Object Oriented Programming
Types of Inheritance
Single Inheritance
In single inheritance, there is a single child class that inherits properties
from one parent class.
Multilevel Inheritance
In this type of inheritance, the child or derived class inherits the features of
the superclass and simultaneously this child class acts as a superclass for
another derived class.
Hierarchical Inheritance
In Hierarchical Inheritance, one class acts as a superclass (base class) for
more than one subclass. More than one subclass can inherit the features of a
base class.
Multiple Inheritance
In Multiple Inheritance, one child or subclass class can have more than one
base class or superclass and inherit features from every parent class which
it inherits. Java does not support multiple inheritances with classes. 126
Object Oriented Programming
Types Of Inheritance

127
Object Oriented Programming
Points to remember related to Inheritance
1)If we create an object of the superclass, we can access only the
members of superclass. We cannot access the subclass members by
creating an object of superclass.
2)If we create an object of the sub class, we can access superclass
members as well as subclass members so in inheritance relation always
create derived class object
3)We cannot extend a class having a private constructor but if we have
the private constructor as well as public constructor then we can extend
superclass to subclass. In this case, the only public constructor will work.
4)Constructor, Static initialization block (SIB), and Instance initialization
block (IIB) of the superclass cannot be inherited to its subclass but they
are executed while creating an object of the subclass.

128
Object Oriented Programming
Member Access Rules in Inheritance
1)A subclass can contain all the members of its superclass, except private
members.
2)The protected and public members of superclass can be accessed by its
subclass, present in the same package or different package.
3)Members of a superclass with no access modifiers (default access level)
can be accessed by subclass present only in the same package.

129
Object Oriented Programming
super keyword
1)The keyword “super” can be used to call an instance variable of the
superclass. When we declare an instance variable in the subclass with the
same name as provided in the superclass.
The syntax to call superclass instance variable is like this:
Syntax
super.variable_name;

130
Object Oriented Programming
2) There are some situations where the methods of the superclass and
the methods of the subclass have the same names, then the super
keyword is used to differentiate the methods of the superclass from
the methods of the subclass.

131
Object Oriented Programming
3) The super keyword also used to invoke the superclass constructor
from the subclass.

132
Object Oriented Programming
Super Keyword at Constructor Level
The super keyword can also be used to invoke or call the parent class
constructor. Constructor are calling from bottom to top (derived class to
base class) and executing from top to bottom(from base class to derived
class).
To establish the connection between base class constructor and derived
class constructors JVM provides two implicit methods they are:
1)Super()
2)Super(...)

133
Object Oriented Programming
super()
Super() It is used for calling super class default constructor from the
context of derived class constructors.
Note:
In Java, default constructor is provided by compiler automatically but it
also adds super() before the first statement of constructor. If you are
creating your own constructor and you do not have either this() or super()
as the first statement, compiler will provide super() as the first statement
of the constructor.
super(...)
Super(...) It is used for calling super class parameterize constructor from
the context of derived class constructor

134
Object Oriented Programming
In inheritance constructor calling rules

135
Object Oriented Programming
Rule 1 and Rule 3
Whenever the derived class constructor want to call default constructor of
base class, in the context of derived class constructors we write super().
Which is optional to write because every base class contains single form
of default constructor
Rule 2 and Rule 4
Whenever the derived class constructor wants to call parameterized
constructor of base class in the context of derived class constructor we
must write super(...). which is mandatory to write because a base class
may contain multiple forms of parameterized constructors.
Note
Whenever we are using either super() or super(...) in the derived class
constructors the super always must be as a first executable statement in
the body of derived class constructor otherwise we get a compile time
error 136
Object Oriented Programming
final keyword in java
In java language final keyword can be used in following way.
1)final Keyword at Variable Level
2)final Keyword at Method Level
3)final Keyword at Class Level

137
Object Oriented Programming
final at variable level
final keyword is used to make a variable as a constant. A variable declared
with the final keyword cannot be modified by the program after
initialization. This is useful to universal constants, such as "PI".
final Keyword at method level
It makes a method final, meaning that sub classes can not override this
method. The compiler checks and gives an error if you try to override the
method.
final Keyword at Class Level
It makes a class final, meaning that the class can not be inheriting by other
classes. When we want to restrict inheritance then make class as a final.

138
Object Oriented Programming
Method Overloading in Java
When a class has more than one method having the same name but
different in parameters, it is called method overloading. In other words,
when multiple methods are declared with the same name but with
different parameter lists, all these methods are said to be overloaded
methods.
Note
1)The return type of a method is not part of the method signature. It does
not play any role in resolving methods overloaded.
2)When a class has multiple methods having the same name with the
different parameter list, the compiler differentiates one method from
another method by checking the different number of parameters or types
of parameters.

139
Object Oriented Programming
Method overloading rules in Java
1)The method name must be the same.
2)Parameters must be different i.e each overloaded method must take a unique list of
parameter types. The parameters can be changed in one of the following three ways.
a. Data types of parameters
void add(int a, int b);
void add(int a, float b);
b. Number of parameters
void sum(int a, int b);
void sum(int a, int b, int c);
c. Sequence of the data type of parameters
void sub(int a, double b);
void sub(double a, float a);
3)Access specifiers can be anything or different.
4)Return type can be anything or different.
5)Exception thrown can be anything.
6)The implementation does not matter in this case. A method can have any kind of logic.

140
Object Oriented Programming
Method overloading is done in java due to the following needs
1)Method overloading is done to reuse the same method name.
2)It is done to make the program logically more readable and
understandable.
3)It is used to achieve the compile-time polymorphism in Java.
Can we overload main() method in Java?
Yes, we can overload the main() method in Java. A class can have any
number of main() methods but JVM calls that main() method that
receives string array as an argument only.
Therefore, the execution always starts from public static void
main(String[] args) only.

141
Object Oriented Programming
Method Overriding in Java
When the superclass method has available to subclass by default through
inheritance and subclass does not satisfy with superclass implementation
then subclass is allowed modifies that base class implementation on its
requirement. This process is called overriding in Java.

The superclass method which is overridden is called overridden method


in java. The subclass method which is overriding the superclass method is
called overriding method in java.

142
Object Oriented Programming
Method Overriding

143
Object Oriented Programming
Importance of Java Method Overriding
One of the benefits of Method Overriding is the ability to provide a
specific implementation or definition of a method in a subclass, which
already exists in its superclass.
It is also useful in the implementation of Runtime or Dynamic
Polymorphism in which the method is invoked during the execution of
the program.

144
Object Oriented Programming
Method overriding rules in Java
1)Subclass method name must be the same as superclass method name.
2)The parameters of subclass method must be the same as superclass
method parameters. i.e In overriding, method name and argument types
must be matched. In other words, the method signature must be the same
or matched.
3)Must be Is-A relationship (Inheritance).
4)Subclass method’s return type must be the same as superclass method
return type.

145
Object Oriented Programming
5) Subclass method’s access modifier must be same or higher than
superclass method access modifier.

6) Only the instance method can be overridden in Java.


7) Overriding concept is not applicable for private, final, static, and
main method in Java.
8) Overriding method cannot throw any checked exception.
146
Object Oriented Programming
@Override annotation in Java
@Override is an annotation which is used by the compiler to check all the rules
of overriding. If we do not write this annotation, the compiler will apply only
three overriding rules such as
1. Superclass and subclass relation.
2. Method name same.
3. Parameters are the same.
But if we have written as @Override on subclass method, the compiler will
apply all rules irrespective of above three points.
For example:
Without annotation
In superclass
private void msg(){
System.out.println(“Hello”);
}
In subclass
private void msg(){
System.out.println(“Hi”)
}
Compile time: ok
Runtime: ok
147
Object Oriented Programming
With annotation
In superclass
private void msg(){
System.out.println(“Hello”);
}
In subclass
@Override
private void msg(){
System.out.println(“Hi”);
}
Compile time: Error- private method cannot be overridden.
Runtime: ok

148
Object Oriented Programming
Upcasting and Downcasting in Java
What is Upcasting (Widening)?
When the reference variable of super class refers to the object of sub class,
it is known as widening or Upcasting in java.
Suppose class One and class Two are related classes through inheritance.
class One is a super class and class Two is sub class of One.
One o = new Two(); // class One’s reference o is pointing to class Two’s
object.
Here, sub class object type has been converted into super class type. This
kind of conversion is called upcasting or widening in java.
Note:
The process of converting sub class type into super class type is called
generalization because we are making the subclass to become more general
so that its scope can be more widening. This conversion is also called
widening or upcasting in java.
149
Object Oriented Programming
Upcasting

150
Object Oriented Programming
Downcasting (Narrowing) in Java
When subclass reference refers to super class object, it is called
narrowing or downcasting in java. In other words, when super class type
is converted into sub class type, it is called downcasting.

Note:
The conversion of a super class type into sub class type is called
specialization in java. Specialization means going down from a more
general form to a more specific form. Thus, its scope will be narrowed.
Hence, this conversion is also called narrowing or down-casting in java.
151
Object Oriented Programming
Generalization and Specialization

152
Object Oriented Programming
Generalization and Specialization
Let us take a super class Mobile and sub classes are Samsung and
Samsung Galaxy as shown in the below figure.
When we talk about a mobile, In general, it may represent any kind of
mobile. So, here, the scope is widened. Now, suppose we talk about
Samsung mobile, then we come down one step in the hierarchy of
inheritance and we have eliminated any other kind of mobiles.
Thus, we are becoming more specific. When we still come down to
Samsung Galaxy, we are pointing only Samsung Galaxy mobile and not
any other Samsung mobile. Thus, this is very specific. This means that
when we move down from super class to sub classes, we are becoming
more and more specific.
When we go back from sub classes to super class, we are becoming more
general. This is called generalization in java. Generalization is safe
because classes will be more general. 153
Object oriented programming
Polymorphism in Java
Polymorphism is a mechanism for getting different characteristics
of the same instance.
For example,
We all know that water is a liquid, but it changes to solid when it
frozen, and it changes to a gas when it is heated at its boiling point.

Java Polymorphism allows us to perform a single task in different


ways. It is used when we have multiple classes that are related to
each other by inheritance.
154
Object oriented programming
Types of Polymorphism
1. Static polymorphism
2. Dynamic polymorphism

155
Object oriented programming
Binding refers to the link between method call and method definition.
In this picture, “a1.methodOne()” call is binding to corresponding methodOne()
definition and “a1.methodTwo()” call is binding to corresponding methodTwo()
definition.

156
Object oriented programming
Static Polymorphism in Java
A polymorphism that exhibited during compilation is
called static polymorphism. In the static polymorphism,
the behavior of a method is decided at binding-time.
Hence, Java compiler binds method calls with method
definition/body during compilation.
Since binding is performed at compile-time, it is also
known as early binding. Compile-time polymorphism can
be achieved/implemented by method overloading in java.

157
Object oriented programming

158
Object oriented programming
In this picture, ‘a1’ is a reference variable of type Class A pointing to object of
class A. ‘a2’ is also reference variable of type class A but pointing to object of
Class B.
During compilation, while binding, compiler does not check the type of object to
which a particular reference variable is pointing. It just checks the type of
reference variable through which a method is called and checks whether there
exist a method definition for it in that type.
For example, for “a1.method()” method call in the above picture, compiler
checks whether there exist method definition for method() in Class A. Because
‘a1′ is Class A type. Similarly, for “a2.method()” method call, it checks whether
there exist method definition for method() in Class A. Because ‘a2′ is also Class
A type. It does not check to which object, ‘a1’ and ‘a2’ are pointing. This type of
binding is called static binding.

159
Object oriented programming
Dynamic Polymorphism in Java
A polymorphism that is exhibited at runtime is called dynamic
polymorphism. In dynamic polymorphism, the behavior of a
method is decided at runtime, therefore, the JVM (Java Virtual
Machine) binds the method call with method definition/body at
runtime and invokes the relevant method during runtime when the
method is called.
This happens at runtime because objects are created at runtime and
the method is called using an object of the class. The Java compiler
has no awareness of the method to be called on an instance during
compilation. Therefore, JVM invokes the relevant method during
runtime.
Dynamic or runtime polymorphism can be achieved/implemented
in java using method overriding. 160
Object oriented programming

161
Object oriented programming
During run time actual objects are used for binding. For
example, for “a1.method()” call in the above picture,
method() of actual object to which ‘a1’ is pointing will be
called. For “a2.method()” call, method() of actual object
to which ‘a2’ is pointing will be called. This type of
binding is called dynamic binding.

162
Object oriented programming
Method Overloading vs Method Overriding in Java
Definition
a. When a class has more than one method having the same name
but different in parameters, it is called method overloading in Java.
b. When the method of superclass is overridden in subclass to
provide more specific implementation, it is called method
overriding in Java.
Argument types
a. Argument type must be different (at least order) in overloading.
b. In overriding, argument type must be the same (including order).

163
Object oriented programming

164
Object oriented programming
Method signature
a. The signature of the overloaded method must be different.
b. The signature of the overriding method must be the same.
Return type
a. In method overloading, the return type can be the same or
different.
b. In method overriding, the return type must be the same until Java
1.4 version but Java 1.5 onwards, method overriding can be done
by changing the covariant return type.
Class
a. Method overloading is generally performed in the same class.
b. Method overriding is performed in two classes through
inheritance (Is-A relationship). 165
Object oriented programming
Private/static/final method
a. Private, static, and final method can be overloaded in Java.
b. Overriding concept is not applicable to private, static, and final
method. Private, static, and final method can not be overridden in
Java.
Access modifiers
a. In overloading, access modifiers can be anything or different.
b. In overriding, subclass method’s access modifier must be same
or higher than superclass method access modifier i.e we cannot
reduce the visibility subclass method while overriding.
Method resolution
a. Method resolution in overloading always takes care by the
compiler based on reference type.
b. Method resolution in overriding always takes care by JVM based
on runtime object. 166
Object oriented programming
Throws clause
a. Exception thrown can be anything in the overloading concept.
b. In case of method overriding, if child class method throws any checked
exception compulsory parent class method should throw the same checked
exception are its parent otherwise we will get compile time error but there is no
restriction for an unchecked exception.
Polymorphism
a. Method overloading is also known as compile-time polymorphism, static
polymorphism, or early binding.
b. Method overriding is also known as runtime polymorphism, dynamic
polymorphism, or late binding.

167
Object Oriented Programming
Covariant Return Types in Java
1)As you know that in the overriding, the return type of subclass method
must be the same as the superclass method return type.
2)But this rule is applicable until Java 1.4 version. In Java 1.5, a new
covariant return types feature was introduced.
3)By using this feature, it is possible to override any method by changing
the return type only if the return type of overriding method in the
subclass is a subtype of the declared return type of overridden method
instead of being exactly the same type.
Note
Covariant return type is applicable for only for object types not for
primitive types.

168
Object Oriented Programming
Covariant Return Types in Java

169
Object Oriented Programming
public class A {
public Object m1() {
System.out.println("Hello, this is a superclass");
return null;
}
}
public class B extends A{
@Override
public String m1() {
System.out.println("Hello, this is the subclass");
return null;
}
}
170
Object Oriented Programming
Method Hiding in Java
A static method (class method) cannot be overridden in Java but if
a static method defined in the parent class is redefined in a child
class, the child class’s method hides the method defined in the
parent class.
This mechanism is called method hiding in Java or function hiding.
The hidden static method can be called using the below syntax:
superClassName.staticMethodName

171
Object Oriented Programming
Method Hiding

172
Object Oriented Programming
class ParentClass {
public static void classMethod(){
System.out.println("classMethod in Parent class");
}
}
class ChildClass extends ParentClass {
public static void classMethod(){
System.out.println("classMethod in Child class");
}
}

173
Abstraction In Java
In object oriented programming abstraction is a
process of providing functionality to the users by hiding
its implementation details from them

In other words, the user will have just the


knowledge of what an entity is doing instead of its
implementation

174
Abstraction In Java
Real life example of Abstraction is ATM Machine; All are
performing operations on the ATM machine like cash
withdrawal, money transfer, retrieve mini-statement…etc.
but we can't know internal details about ATM.

175
Abstraction In Java
Advantages of Abstraction

176
Abstraction In Java
How to Achieve Abstraction in Java?
In Java, we can achieve Data Abstraction using Abstract
class and Interface
Interface allow 100% abstraction(complete abstraction).
Interface allow you to abstract the implementation
completely
Abstract class allow 0 to 100% abstraction (partial to
complete abstraction)because abstract class can contain
concrete methods that have the implementation which
results in a partial abstraction

177
Abstraction In Java
In Java programming we have two types of classes they
are
1)Concrete class
2)Abstract class
A concrete class is one which is containing fully defined
methods or implemented method.
class Helloworld{
void display(){
System.out.println("Good Morning........");
}
} 178
Abstraction In Java
Abstract class
A class that is declared with abstract keyword, is known as abstract
class. An abstract class is one which is containing some defined
method and some undefined method. In java programming
undefined methods are known as un-Implemented, or abstract
method.
Syntax
abstract class className{
......
}
Example
abstract class A{
..... 179
Abstraction In Java
Abstract method
An abstract method is one which contains only
declaration or prototype but it never contains body or
implementation. In order to make any method as abstract
whose declaration is must be predefined by abstract
keyword. The declaration of an abstract method must end
with a semicolon;
Syntax
abstract ReturnType methodName(List of formal
parameter);
Example
abstract void Bike(); 180
Abstraction In Java
Rules for Using Abstract Class in Java
1)We can declare an abstract class using the abstract
keyword.
2)It may have abstract as well as concrete (non-abstract)
methods.
3)An abstract class can have static methods.
4)An abstract class can also have constructors.
5)It can have final methods. If we declare the method as
final inside the abstract class then the subclass can not
change the body of the method.

181
Abstraction In Java
6) We can’t instantiate or create an object of an abstract
class.
7) A class derived from the abstract parent class must
implement each method that is declared as abstract in
the parent class. Otherwise, there will be a
compilation error.
8) If the derived class does not implement all the abstract
methods of an abstract parent class, then the derived
class must also declare itself as abstract.

182
Abstraction In Java
Why do we need Abstract Classes in Java?
We want to create a class that just declares the methods without
providing a complete implementation of every method. And, we
want that this method(s) is shared by all of its child classes, and all
the implementation details will be filled by these subclasses.
Let’s take the example of a banking application or software.
Suppose we have a class BankAccount that has a method deposit()
and withdraw() and the subclasses of it like SavingsAccount,
CurrentAccount, FixedDepositAccount, etc. Since the process of
deposit and withdrawal differs from one account to another, there is
no point to implement these two methods in the parent class
BankAccount. This is because every child class must override these
methods and provide an implementation of them.
183
Abstraction In Java

184
Abstraction In Java
Interface In Java
1)In Java, an interface is a blueprint or template of a class
used to achieve 100%abstraction.
2)When you create an interface, you're defining a contract
for what a class can do, without saying anything about
how the class will do it.
3)There can be only abstract methods in an interface.
4)If a class implements an interface and does not provide
method bodies for all functions specified in the interface,
then the class must be declared abstract.

185
Abstraction In Java
Syntax to create an interface
interface interface-name{
//abstract methods
}
Example
interface Animal{
public void eat();
public void travel();
}

186
Abstraction In Java
Why we do use interface?

187
Abstraction In Java
Properties of a Java Interface
1)An interface is implicitly abstract. While declaring an interface, you
do not need to use the keyword abstract.
2)Each method of an interface is implicitly public and abstract, so we
need not use the public and abstract keyword while declaring methods
inside an interface.
The following five method declarations are legal and identical
a)void bounce();
b)public void bounce();
c)abstract void bounce();
d)public abstract void bounce();
e)abstract public void bounce();
188
Abstraction In Java
3) All variables defined in an interface are public, static, and final.
In other words, interfaces can declare only constants, not
instance variables.
Legal interface constants declarations
a) public int x = 1; // Looks non-static and non-final, // but isn't!
b) int x = 1; // Looks default, non-final, // non-static, but isn't!
c) static int x = 1; // Doesn't show final or public
d) final int x = 1; // Doesn't show static or public
e) public static int x = 1; // Doesn't show final
f) public final int x = 1; // Doesn't show static
g) static final int x = 1 // Doesn't show public

189
Abstraction In Java

190
Abstraction In Java
4) An interface can extend one or more other interfaces.

5) A class can extend only one class (no multiple


inheritance), but it can implement one or more
interfaces.

191
Abstraction In Java
1) class Foo { }
class Bar implements Foo { }

2) interface Baz { }
interface Fi { }
interface Fee implements Baz { }

3) class Foo { }
interface Zee implements Foo { }

4) class Foo
interface Zoo extends Foo { }
192
Abstraction In Java
5) interface Fi { }
interface Boo extends Fi { }
6) class Toon extends Foo, Button { }
7) class Zoom implements Fi, Baz { }
8) interface Vroom extends Fi, Baz { }
9)class Yow extends Foo implements Fi { }

193
Abstraction In Java
How interface is different from class ?
1)You can not instantiate an interface.
2)It does not contain any constructors.
3)All methods in an interface are abstract.
4)Interface can not contain instance fields. Interface only
contains public static final variables.
5)Interface is can not extended by a class; it is
implemented by a class.
6)Interface can extend multiple interfaces. It means
interface exhibit the functionality multiple inheritance
194
Abstraction In Java
Implementing Interfaces in Java
A class implementing an interface it means that the class
agrees to perform the specific behaviors of the interface.
Unless a class is declared as abstract, it should perform all
the behaviors of the interface.
In order to implement an interface, a class uses the
implements keyword.
public class Ball implements Bounceable {
public void bounce() { }
public void setBounceFactor(int bf) { }
}
195
Abstraction In Java
When we use abstract and when Interface
If we do not know about any things about implementation just we
have requirement specification then we should be go for Interface
If we are talking about implementation but not completely
(partially implemented) then we should be go for abstract
Why interface have no constructor ?
Because, constructor are used for eliminate the default values by
user defined values, but in case of interface all the data members
are public static final that means all are constant so no need to
eliminate these values.
Other reason because constructor is like a method and it is concrete
method and interface does not have concrete method it have only
abstract methods that's why interface have no constructor.
196
Abstraction In Java

197
Abstraction In Java

198
Abstraction In Java
Marker or tagged interface
An interface that have no member is known as marker or
tagged interface. For example: Serializable, Cloneable,
Remote etc. They are used to provide some essential
information to the JVM so that JVM may perform some
useful operation.
Example
//Way of writing Serializable interface
public interface Serializable
{
}
199
Abstraction In Java
New features added in interfaces from JDK 8 version
1) Java 8 allows the interfaces to have default and static
methods.
Why Default methods?
Classes such as A, B, C and D implements an interface XYZ Interface. If we add
a new method to the XYZ Interface, we have to change the code in all the
classes(A, B, C and D) that implements this interface. Here, we have only four
classes that implements the interface which we want to change but imagine if
there are hundreds of classes implementing an interface then it would be almost
impossible to change the code in all those classes. This is why in java 8, we have
a new concept “default methods”. These methods can be added to any existing
interface and we do not need to implement these methods in the implementation
classes mandatorily, thus we can add these default methods to existing interfaces
without breaking the code.

200
Abstraction In Java
Why static methods?
Static methods in interfaces are similar to the default
methods except that we cannot override these methods in
the classes that implements these interfaces.

201
Abstraction In Java
Interface with default method
interface MyInterface{
/* This is a default method so we need not
* to implement this method in the implementation
* classes
*/
default void newMethod(){
System.out.println("Newly added default method");
}
/* Already existing public and abstract method
void existingMethod(String str);
}
202
Abstraction In Java
Interface with static method
interface MyInterface{
default void newMethod(){
System.out.println("Newly added default method");
}
/* This is a static method. Static method in interface is
static void anotherNewMethod(){
System.out.println("Newly added static method");
}
//Already existing public and abstract method
void existingMethod(String str);
}
203
Abstraction In Java
Default Method and Multiple Inheritance
The multiple inheritance problem can occur, when we have two interfaces with
the default methods of same signature. Lets take an example.
interface MyInterface{
default void newMethod(){
System.out.println("Newly added default method");
} void existingMethod(String str);
}
interface MyInterface2{
default void newMethod(){
System.out.println("Newly added default method");
}void disp(String str);
}
How to solve this issue?
To solve this problem, we can implement this method in the implementation
class
204
Abstraction In Java
Java 9 has introduced another new feature, Java 9 SE
onwards we can have private methods in interfaces.

Java 9 introduced private methods in interfaces to remove


the redundancy by sharing the common code of multiple
default methods through private methods.

205
Abstraction In Java
Multiple default methods with duplicate code (java8)
interface MyInterfaceInJava8 {
default void method1() {
System.out.println("Starting method");
System.out.println("Doing someting");
System.out.println("This is method1");
}
default void method2() {
System.out.println("Starting method");
System.out.println("Doing someting");
System.out.println("This is method2");
}
}

206
Abstraction In Java
Default methods sharing common code using private methods
interface MyInterfaceInJava9 {
default void method1() {
//calling private method
printLines();
System.out.println("This is method1");
}
default void method2() {
//calling private method
printLines();
System.out.println("This is method2");
}
private void printLines() {
System.out.println("Starting method");
System.out.println("Doing someting");
}
}
207
Abstraction In Java
Java 9 also allows us to have private static methods in
interfaces.

Since java 8 we can have static methods in interfaces


along with default methods. We can not share the
common code of static methods using the non-static
private method, we must have to use the private static
method to do that.

208
Abstraction In Java
interface MyInterfaceInJava9 {
static void method1() {
printLines(); //calling private method
System.out.println("This is method1");
}
static void method2() {
printLines(); //calling private method
System.out.println("This is method2");
}
//this must be static else we will get compilation error
private static void printLines() {
System.out.println("Starting method");
System.out.println("Doing someting");
}
default void mymethods() {
method1();
method2();
}
}
209
Object Oriented Programming
Factory Method or Factory Method Design Pattern
The factory design pattern is used when we have a
superclass with multiple sub-classes and based on input,
we need to return one of the sub-class.
This pattern takes out the responsibility of the
instantiation of a class from the client program to the
factory class.

210
Object Oriented Programming
Factory Design Pattern Super Class
Super class in factory design pattern can be an interface, abstract class or a
normal java class.
public abstract class Computer {
public abstract String getRAM();
public abstract String getHDD();
public abstract String getCPU();
//toString() method
}

211
Object Oriented Programming
Factory Design Pattern Sub Classes
public class PC extends Computer {
private String ram;
private String hdd;
private String cpu;
//parameterized constructor
@Override
public String getRAM() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}
212
Object Oriented Programming
public class Server extends Computer {
private String ram;
private String hdd;
private String cpu;
//parameterized constructor
@Override
public String getRAM() {
return this.ram;
}
@Override
public String getHDD() {
return this.hdd;
}
@Override
public String getCPU() {
return this.cpu;
}
}

213
Object Oriented Programming
Factory Class
public class ComputerFactory {
public static Computer getComputer(String type, String ram, String hdd,
String cpu){
if("PC".equalsIgnoreCase(type))
return new PC(ram, hdd, cpu);
else if("Server".equalsIgnoreCase(type))
return new Server(ram, hdd, cpu);
return null;
}
}

214
Object Oriented Programming
public class TestFactory {
public static void main(String[] args) {
Computer pc = ComputerFactory.getComputer("pc","2 GB","500
GB","2.4 GHz");
Computer server = ComputerFactory.getComputer("server","16 GB","1
TB","2.9 GHz");
System.out.println("Factory PC Config::"+pc);
System.out.println("Factory Server Config::"+server);
}
}

215
Object Oriented Programming
Inner Classes in Java
1)So far we have seen the members of the class are variables,
methods, constructors, and initializer blocks. But it is also possible
to have a class or an interface as a member of a class.
2)A class declared inside another class is known as nested class.
The class which is a member of another class can be either static or
non-static.
3)The member class which is declared as static is known as static
nested class. The member class which is non-static is known as an
inner class or non-static nested class.

216
Object Oriented Programming
Inner Classes in Java

217
Object Oriented Programming
Need of inner class with an example
class Account{
private double balance;
public Account(double balance) {
this.balance = balance;
}
public double calculateInterest(double interestRate) {
double interest=balance*interestRate/100;
balance=balance+interest;
return balance;
}
}
There is no security for above code, because above class having default access
level, so any other programmer can easily create an object to this class and
access the calculateInterest()method with any interest rate value as shown
below

218
Object Oriented Programming
public class ModifieAccount {
public static void main(String[] args) {
Account savingAccount=new Account(5000);
double totalBalance=savingAccount.calculateInterest(7.5);
System.out.println("Balance after adding interest="+totalBalance);
}
}

219
Object Oriented Programming
Solution for above problem
The way to provide security to calculateInterest() method and the rate of interest is to
write them inside a class Interest and make it a private inner class in Account class as
shown below
class Account{
private double balance;
public Account(double balance) {
this.balance = balance;
}
private class Interest{
private double intersetRate;
public Interest(double intersetRate) {
this.intersetRate = intersetRate;
}
public double calculateInterest(double interestRate) {
double interest=balance*interestRate/100;
balance=balance+interest;
return balance;
}
}
}
220
Object Oriented Programming
Types of inner classes

221
Object Oriented Programming
Nested Inner Class in Java
A non-static class that is declared inside a class but outside the method is known
as nested inner class in Java.
It is also known as regular inner class. It can be declared with access modifiers
like public, default, private, and protected.
Syntax:
class Outer {
// A member inner class named Inner.
class Inner {
........
}
}
When we compile the class like this javac Outer.java, the compiler will generate
two separate dot class files like this Outer.class for outer class and
Outer$Inner.class for the inner class
222
Object Oriented Programming
Syntax to create object of Inner class in Java
An instance of an inner class shares a relationship with an instance of an outer
class.
So to create an object of inner class, you must first have to create an object of
outer class to tie to the inner class. We can create multiple objects of an inner
class for the same instance of an outer class.
Syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
For example:
// First create an object of Outer class Test.
Test t = new Test();
// Second create an object of inner class A.
Test.A innerObj = t.new A();

223
Object Oriented Programming

224
Object Oriented Programming
Method local inner class
1) An inner class that is declared inside a method of the outer class is
called method local inner class in Java. Its scope is limited to the block
of a method in which it is declared.
2) Therefore, the declaration of method local inner class cannot use any
access modifiers such as public, protected, private, and non-access
modifiers such as static.
3) Method local inner class in Java can also be declared inside the
constructor, static initializers, and non-static initializers.
4) The only applicable modifiers for the method local inner class are
final, abstract, and strictfp.

225
Object Oriented Programming

226
Object Oriented Programming
Static nested class
When an inner class is defined with a static modifier inside the body of
another class, it is known as a static nested class in Java.
Syntax:
// A top-level class.
public class Outer{
// Static member class.
public static class Nested{
// Body for class Nested.
}
}
Since it is a static nested class, we do not need an instance of its outer
class to create its object. An object of class Outer and an object of class
Nested can exist independently because both are top-level classes. 227
Object Oriented Programming
Relationship between Static Nested class, Inner class with Outer class
object

228
Object Oriented Programming
How to access Static and Non-static members of Outer class from Static
nested class

229
Object Oriented Programming
Anonymous Inner Class in Java
1)An anonymous inner class is an inner class which is declared
without any class name at all. In other words, a nameless inner
class is called an anonymous inner class in Java.
2)Since it does not have a name, it cannot have a constructor
because you know that a constructor name is the same as the class
name.

230
Object Oriented Programming
How to create object of anonymous inner class in Java?
We define an anonymous inner class and create its object using the new
operator at the same time in one step.
The general syntax of the declaration of an anonymous class and its
object.
Syntax:
new<interface-name or class-name>(argument-list)
{
// Anonymous class body
}

231
Object Oriented Programming
1) The new keyword is used to create an object of the anonymous inner
class. It is always followed by either an existing class name or an
existing interface name.
2) In the above syntax, if an interface name is used, it means that the
anonymous class implements the interface. If a class name is used, it
means that the anonymous class extends from the class.
3) It the new keyword is followed by a class name then the argument list
is used only. The argument list contains the actual parameter list
which is used for calling a constructor of the existing class. If the
new keyword is followed by an interface name, it is left empty.
4) Inside an anonymous class body, we can define variables, methods (if
necessary), instance block, and local class.

232
Object Oriented Programming
When to use an Anonymous inner class in Java?
1)The main purpose of using an anonymous inner class in java is
just for instant use (i.e one-time usage).
2)An anonymous inner class can be used if the class has a very
short body.
3)It can be useful if only one object of the class is required.
4)An anonymous inner class is the best suitable for GUI based
application to implement event handling.

233
Object Oriented Programming
Features of Anonymous Inner Class in Java
1)When an anonymous inner class is created, Internally, its name is
decided by the compiler which always extends a superclass or
implements an interface. But it cannot have an explicit extends or
implements clause.
2)It must implement all the abstract methods of the superclass or of the
interface.
3)Internally, it always uses a default constructor from its superclass to
create an object.
4)An anonymous inner class is compiled by a class named
OuterClassName$n. For example, if the outer class Student has two
anonymous inner classes, they are compiled into Student$1.class and
Student$2.class.
5)An anonymous inner class can also access the members of its outer
class. 234
Object Oriented Programming
Types of Anonymous Inner Class in Java
Based on declaration and behavior, an anonymous inner class in
Java comes into two flavors. They are as follows:
1)Anonymous inner class that extends a class
2)Anonymous inner class that implements an interface

235
Object Oriented Programming
Anonymous inner class that extends class
public class Fruits{
public void mango(){
System.out.println("Sweet");
}
}
Suppose we need mango sour taste for a one-time temporary requirement.
There are two ways by which we can implement in the above code.
1)We will create a class that will extend the Fruits class and overrides the
mango method. But this technique is suitable for the permanent
requirement, not for the temporary requirement.
2)We will use an anonymous inner class concept for a one-time
temporary requirement.
236
Object Oriented Programming
public class Taste {
public static void main(String[] args) {
// Here, we are using an anonymous inner class that extends a class Fruits.
Fruits f = new Fruits() {
// Here, Overriding the mango() method of Fruits class.
public void mango() {
System.out.println("Sour"); // Overriding.
}
}; // Anonymous inner class ends here. A semi-colon is necessary to
end the statement.
f.mango();
// This object is created for Fruits class.
Fruits f1 = new Fruits();
f1.mango(); // It will print sweet.
}
} 237
Object Oriented Programming

238
Object Oriented Programming
1) In line 1, Fruits f = new Fruits() { tells us that an object of the
anonymous class is created that is referred by a reference variable f
of type Fruits. Then declare a new class but its name is decided by
the compiler that extends the fruits class and provides the
implementation (i.e overriding) of mango() method.In line 1, there is
also a curly brace that opens the class definition.
2) In line 2, within the new class definition, we are overriding the
mango() method of the superclass Fruits.
3) In line 4, Statement within the overriding mango() method.
4) In line 5, we are closing curly brace of the mango() method.
5) Line 6 includes a curly brace closing off the anonymous inner class
definition. But curly brace also contains semicolon that ends the
statement started on line 1.

239
Object Oriented Programming
Dot class file generated by the compiler:
1)There is a total of three dots class file generated by the compiler.1. First
dot class file generated by the compiler for Fruits class is Fruits.class.
2)Second dot class file generated by the compiler for Taste class is
Taste.class.
3)One dot class file is also generated for the anonymous inner class.
Since it is present in the Taste class.
4)Therefore, Taste class is the outer class of the anonymous inner class.
So, the dot class file for the anonymous inner class is Tatse$1.class. 1
represents the first anonymous inner class.

240
Object Oriented Programming
Internal class generated by the compiler:
static class Taste$1 extends Fruits {
Taste$1() {
}
public void mango() {
System.out.println("Sour");
}
}

241
Object Oriented Programming
Anonymous inner class that implements interface
public interface Animal {
// Abstract method does not have a body.
public void food(); // No body.
}
public class Lion{
// Here, we are using an anonymous inner class that implements an interface Animal.
Animal a = new Animal() {
public void food() {
System.out.println("Lion eats flesh"); // Overriding food method of Interface Animal.
}
};
public void display() {
a.food();
}
}
242
Object Oriented Programming
public class Test {
public static void main(String[] args){
Lion l = new Lion();
l.display(); // 1st method to call an anonymous function by local class
method.
l.a.food(); // 2nd method to call an anonymous function directly.
}
}

243
Object Oriented Programming

244
Object Oriented Programming
Internal class generated by the compiler:
static class Lion$1 implements Animal {
Lion$1() {
}
public void food()
{
System.out.println("Lion eats flesh");
}
}

245
Object Oriented Programming
Restriction on Anonymous inner class in Java
1)Anonymous inner class cannot be public, private, protected or static.
2)It cannot access the local variables of its enclosing scope that are not
declared as final or effectively final.
3)Inside anonymous inner classes, we cannot define any static variables,
methods, or static blocks except for static final constant.
4)We cannot create more than one object of the anonymous inner class in
Java.
5)Since an anonymous inner class has no name. Therefore, we cannot
declare a constructor for it within the class body.

246
Object Oriented Programming
Difference between Normal/Regular class and Anonymous Inner class
1)A normal Java class can implement any number of interfaces
simultaneously but an anonymous inner class can implement only one
interface at a time.
2)A normal Java class can extend a class and can implement any number
of interfaces simultaneously but an anonymous inner class can extend a
class or can implement an interface but not both simultaneously.
3)In normal Java class, we can define any number of constructors but in
an anonymous inner class, we cannot write any constructor explicitly
(because the name of the class and name of the constructor must be the
same but anonymous inner class not having any name).

247
Object Oriented Programming
Method Local Inner Classses

248
Object Oriented Programming

249
Object Oriented Programming

250
Object Oriented Programming

251
Object Oriented Programming

252
Object Oriented Programming

253
Object Oriented Programming

254
Object Oriented Programming

255
Java8 Features
Java Lambda Expressions
1)Lambda expression is a new feature which is introduced in Java 8.
2) A lambda expression is an anonymous function. A function that
doesn’t have a name and doesn’t belong to any class.
Java Lambda Expression Syntax
1)To create a lambda expression, we specify input parameters (if there
are any) on the left side of the lambda operator ->, and place the
expression or block of statements on the right side of lambda operator.
For example, the lambda expression (x, y) -> x + y specifies that lambda
expression takes two arguments x and y and returns the sum of these.
//Syntax of lambda expression
(parameter_list) -> {function_body}

256
Java8 Features
Lambda expression vs method in Java
A method (or function) in Java has these main parts:
1. Name 2. Parameter list 3. Body 4. return type.
A lambda expression in Java has these main parts:
1. No name – function is anonymous so we don’t care about the name
2. Parameter list
3. Body – This is the main part of the function.
4. No return type – The java 8 compiler is able to infer(understand) the
return type by checking the code. you need not to mention it explicitly.

257
Java8 Features
Where to use the Lambdas in Java
To use lambda expression, you need to either create your own functional
interface or use the pre defined functional interface provided by Java.
An interface with only single abstract method is called functional
interface(or Single Abstract method interface), for example: Runnable,
callable, ActionListener etc.

258
Java8 Features
Java Functional Interfaces
1)An interface with only single abstract method is called functional
interface.
2)You can either use the predefined functional interface provided by Java
or create your own functional interface and use it.
3)You know more about predefined functional interfaces:
'https://docs.oracle.com/javase/8/docs/api/java/util/function/package-
summary.html'
4)Predefined functional interfaces they all have only one abstract method.
That is the reason, they are also known as Single Abstract Method
interfaces (SAM Interfaces).

259
Java8 Features
5) While creating your own functional interface, mark it with
@FunctionalInterface annotation, this annotation is introduced in
Java 8.
6) Although its optional, you should use it so that you get a compilation
error if the interface you marked with this annotation is not following
the rules of functional interfaces.
7) The functional interface should have Only one abstract method.
Along with the one abstract method, they can have any number of
default and static methods.

260
Java8 Features
Method Reference
Method reference is a shorthand notation of a lambda expression to call a
method.
For example: If your lambda expression is like this:
str -> System.out.println(str)
then you can replace it with a method reference like this:
System.out::println
The :: operator is used in method reference to separate the class or object
from the method name
Method Reference Syntax
The method reference has two parts – class/object and
method/constructor. They are separated by double colons (::). There are
no additional parameters passed with the method reference.
261
Java8 Features
Types of method references

262
Java8 Features
Optional class
1)In Java 8, we have a newly introduced Optional class in java.util
package.
2)This class is introduced to avoid NullPointerException that we
frequently encounters if we do not perform null checks in our code.
3)Using this class we can easily check whether a variable has null
value or not and by doing this we can avoid the
NullPointerException.

263
Java8 Features
public class Example {
public static void main(String[] args) {
String[] str = new String[10];
//Getting the substring
String str2 = str[9].substring(2, 5);
//Displaying substring
System.out.print(str2);
}
}
Output:
Exception in thread "main" java.lang.NullPointerException
at Example.main(Example.java:5)

264
Java8 Features
How to create Optional Object in Java 8
You can create an empty Optional by using the static method
Optional.empty()
Optional<Person> p = Optional.empty(); //This Optional is empty

You can also create an instance of the Optional class by using the static
factory method Optional.of() in Java 8 as shown in the following
example:
Address home = new Address(block, city, state, country, pincode);
Optional<Address> = Optional.of(home);
This code will return an Optional of Address object but value i.e. home
must be not-null. In case the object is null then Optional.of() method will
throw NullPointerException.

265
Java8 Features
Third and probably the most useful way of creating an Optional instance
is by using the ofNullable() method of java.util.Optional class which
allows you to create an Optional object that may hold a null value
Optional<Person> op = Optional.ofNullable(p);
In case the Person object is null, the resulting Optional object would be
empty, but it won't throw the NullPointerException.

266
Java8 Features
Optional isPresent() vs ifPresent() methods
isPresent() method can check whether the particular Optional object(or
instance) is empty or no-empty.
Optional<String> GOT = Optional.of("Game of Thrones");
if (GOT.isPresent()) {
System.out.println("Watching Game of Thrones");
}
else {
System.out.println("I am getting Bored");
}

267
Java8 Features
ifPresent() method only executes if the given Optional object is non-
empty.
Optional<String> nothing = Optional.empty();
GOT.ifPresent(s -> System.out.println("Watching GOT is fun!"));
//This will not print as the nothing is empty
nothing.ifPresent(s -> System.out.println("I prefer getting bored"));

268
Java8 Features
Optional orElse() and orElseGet() methods
These two methods orElse() and orElseGet() returns the value of Optional
Object if it is not empty, if the object is empty then it returns the default
value passed to this method as an argument.
Optional<String> GOT = Optional.of("Game of Thrones");
Optional<String> nothing = Optional.empty();
System.out.println(GOT.orElse("Default Value")); //Game of Thrones
System.out.println(nothing.orElse("Default Value"));//Default Value
//orElseGet() method
System.out.println(GOT.orElseGet(() -> "Default Value"));//Game of
Thrones
System.out.println(nothing.orElseGet(() -> "Default Value"));//Default
Value
269
Java8 Features
T get(): This method is used to get the value from optional. It returns the
value, If the value is present in this Optional, otherwise throws
NoSuchElementException.
For example,
Optional<String> objOfOptional = Optional.of("Hi");
System.out.println(objOfOptional.get());

270
Java8 Features
Optional<T> filter(Predicate<? super T> predicate): This method
returns an object of Optional. If the value in present and matched with
given Predicate. Otherwise, it returns an empty Optional.
For example,
Optional<String> obj = Optional.of("Hello");
Optional<String> objByFilter = obj.filter(a -> a.equals("Hello"));
System.out.println("Is this empty optional = "+
objByFilter.isPresent());
Optional<String> objByFilter1 = obj.filter(a -> a.equals("Hi"));
System.out.println("Is this empty optional = "+
objByFilter1.isPresent());

271
Java8 Features
Stream API
1)Stream API which is another new feature of java 8. All the classes and
interfaces of this API is in the java.util.stream package.
2)By using streams we can perform various aggregate operations on the
data returned from collections, arrays, Input/Output operations.

272
Java8 Features
Find out number of string having length less than 6
List<String> names = new ArrayList<String>();
names.add("Ajeet");
names.add("Negan");
names.add("Aditya");
names.add("Steve");
int count = 0;
for (String str : names) {
if (str.length() < 6)
count++;
}
System.out.println("There are "+count+" strings with length less
than 6")
273
Java8 Features
Find out number of string having length less than 6 with Stream API
List<String> names = new ArrayList<String>();
names.add("Ajeet");
names.add("Negan");
names.add("Aditya");
names.add("Steve");

//Using Stream and Lambda expression


long count = names.stream().filter(str->str.length()<6).count();
System.out.println("There are "+count+" strings with length less
than 6");

274
Java8 Features
What is the difference between these codes?
In the first example, we are iterating the whole list to find the strings with
length less than 6. There is no parallelism in this code.
In the second example, the stream() method returns a stream of all the
names, the filter() method returns another stream of names with length
less than 6, the count() method reduces this stream to the result.
All these operations are happening parallelly which means we are able to
parallelize the code with the help of streams. Parallel execution of
operations using stream is faster than sequential execution without using
streams.

275
Java8 Features
How to work with Stream in Java
As we have seen in the above example, the working of stream can be
explained in three stages:
1. Create a stream
2. Perform intermediate operations on the initial stream to transform it
into another stream and so on on further intermediate operations. In the
above example, the filter() operation is intermediate operation, there can
be more than one intermediate operations.
3. Perform terminal operation on the final stream to get the result. In the
above example, the count() operation is terminal operation.

276
Java8 Features
Java Stream Features
1)Stream does not store the elements. it simply performs the aggregate
operations(such as filter() and count() that we have seen in the above
example) to get the desired stream of data.
2)The aggregate operations that we perform on the collection, array or
any other data source do not change the data of the source, they simply
return a new stream. For example the code we have seen above is
filtering the strings with length less than 6 using the stream operations but
it didn’t change the elements of the list.
3)All the stream operations are lazy in nature which means they are not
executed until they are needed. For example, if we want to display only
the first 2 elements of a list using stream, the stream operation would stop
at the end of second iteration after displaying the second element of list.

277
Java8 Features
Java Stream Creation
Obtain a stream from an existing array
private static Employee[] arrayOfEmps = {
new Employee(1, "Jeff Bezos", 100000.0),
new Employee(2, "Bill Gates", 200000.0),
new Employee(3, "Mark Zuckerberg", 300000.0)
};
Stream.of(arrayOfEmps);
Obtain a stream from an existing list
private static List<Employee> empList = Arrays.asList(arrayOfEmps);
empList.stream();

278
Java8 Features
We can create a stream from individual objects using Stream.of()
Stream.of(arrayOfEmps[0], arrayOfEmps[1], arrayOfEmps[2]);
Using Stream.builder()
Stream.Builder<Employee> empStreamBuilder = Stream.builder();
empStreamBuilder.accept(arrayOfEmps[0]);
empStreamBuilder.accept(arrayOfEmps[1]);
empStreamBuilder.accept(arrayOfEmps[2]);
Stream<Employee> empStream = empStreamBuilder.build();

279
Java8 Features
Stream Operations
List<String> memberNames = new ArrayList<>();
memberNames.add("Amitabh");
memberNames.add("Shekhar");
memberNames.add("Aman");
memberNames.add("Rahul");
memberNames.add("Shahrukh");
memberNames.add("Salman");
memberNames.add("Yana");
memberNames.add("Lokesh");

280
Java8 Features
Intermediate Operations
Intermediate operations return the stream itself so you can chain multiple
methods calls in a row.
Stream.filter()
The filter() method accepts a Predicate to filter all elements of the stream.
This operation is intermediate which enables us to call another stream
operation (e.g. forEach()) on the result.
memberNames.stream().filter((s) -> s.startsWith("A"))
.forEach(System.out::println);

281
Java8 Features
Stream.map()
The map() intermediate operation converts each element in the stream
into another object via the given function.
The following example converts each string into an UPPERCASE string.
But we can use map() to transform an object into another type as well.
memberNames.stream().filter((s) -> s.startsWith("A"))
.map(String::toUpperCase)
.forEach(System.out::println);

282
Java8 Features
Stream.sorted()
The sorted() method is an intermediate operation that returns a sorted
view of the stream. The elements in the stream are sorted in natural order
unless we pass a custom Comparator.
memberNames.stream().sorted()
.map(String::toUpperCase)
.forEach(System.out::println);
Please note that the sorted() method only creates a sorted view of the
stream without manipulating the ordering of the source Collection.

283
Java8 Features
Terminal operations
Terminal operations return a result of a certain type after processing all
the stream elements.
Once the terminal operation is invoked on a Stream, the iteration of the
Stream and any of the chained streams will get started. Once the iteration
is done, the result of the terminal operation is returned.

Stream.forEach()
The forEach() method helps in iterating over all elements of a stream and
perform some operation on each of them. The operation to be performed
is passed as the lambda expression.
memberNames.forEach(System.out::println);

284
Java8 Features
Stream.collect()
The collect() method is used to receive elements from a steam and store
them in a collection.
List<String> memNamesInUppercase = memberNames.stream().sorted()
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.print(memNamesInUppercase);

285
Java8 Features
Stream.match()
Various matching operations can be used to check whether a given
predicate matches the stream elements. All of these matching operations
are terminal and return a boolean result.
boolean matchedResult = memberNames.stream()
.anyMatch((s) -> s.startsWith("A"));
System.out.println(matchedResult);
matchedResult = memberNames.stream()
.allMatch((s) -> s.startsWith("A"));
System.out.println(matchedResult);
matchedResult = memberNames.stream()
.noneMatch((s) -> s.startsWith("A"));
System.out.println(matchedResult);
286
Java8 Features
Stream.count()
The count() is a terminal operation returning the number of elements in
the stream as a long value.
long totalMatched = memberNames.stream()
.filter((s) -> s.startsWith("A"))
.count();
System.out.println(totalMatched);

287
Java8 Features
Stream.reduce()
The reduce() method performs a reduction on the elements of the stream
with the given function. The result is an Optional holding the reduced
value.

In the given example, we are reducing all the strings by concatenating


them using a separator #.

Optional<String> reduced = memberNames.stream()


.reduce((s1,s2) -> s1 + "#" + s2);

reduced.ifPresent(System.out::println);

288
Java8 Features
The map() function is a method in the Stream class that represents a
functional programming concept.
In simple words, the map() is used to transform one object into another
by applying a function.
That’s the reason the Stream.map(Function mapper) takes a function as
an argument.
For example, by using the map() function, you can convert a list of String
into a List of Integer by applying the Integer.valueOf() method to each
String on the input list.
For example,
List<String> G7 = Arrays.asList("USA", "Japan", "France", "Germany",
"Italy", "U.K.","Canada");
String G7Countries = G7.stream() .map(x -> x.toUpperCase())
.collect(Collectors.joining(", "));
289
Java8 Features
The filter method essentially selects elements based upon a condition you
provide.
That’s the reason that the filter (Predicate condition) accepts a Predicate
object, which provides a function that is applied to a condition.
If the condition evaluates true, then the object is selected. Otherwise, it
will be ignored.
For example,
If your list contains numbers and you only want numbers, then you can
use the filter method to only select a number that is fully divisible by two.
List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");
long count = strList.stream() .filter(x -> x.isEmpty()) .count();

290
Java8 Features
Filter Example1: Counting Empty String
List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");
long count = strList.stream()
.filter(x -> x.isEmpty())
.count();
Filter Example 2: Count String whose length is more than three
List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");
long num = strList.stream()
.filter(x -> x.length()> 3)
.count();

291
Java8 Features
Filter Example 3: Count number of String which starts with "a"
List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");
long count = strList.stream()
.filter(x -> x.startsWith("a"))
.count();

292
Java8 Features
Collectors Example: Remove all empty Strings from List
Here we are again using filter() method to create a subset of all string,
which is non-empty, but instead of counting, we are now calling static
utility method Collectors.toList() to return them as List.
List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");
List<String> filtered = strList.stream()
.filter(x -> !x.isEmpty())
.collect(Collectors.toList());
The Collectors class is very similar to the java.util.Collections class, full
of static methods, which you can use along with Collection. You can
wrap filtered elements into a Set or List by using the Collectors class.

293
Java8 Features
Collectors Example 2: Create a List with String more than 2 characters
List<String> strList = Arrays.asList("abc", "", "bcd", "", "defg", "jk");
List<String> filtered = strList.stream()
.filter(x -> x.length()> 2)
.collect(Collectors.toList());

294
Java8 Features
Map Example 2: Create List of the square of all distinct numbers
Here we are mapping each element to their square and then filtering out
all duplicate elements by calling distinct() method.

List<Integer> numbers = Arrays.asList(9, 10, 3, 4, 7, 3, 4);


List<Integer> distinct = numbers.stream()
.map( i -> i*i)
.distinct()
.collect(Collectors.toList());

Finally, by using the collect() method, we are gathering output into a List.

295
Java8 Features
Statistics Example: Get count, min, max, sum, and the average for
numbers
We will learn how to get some statistical data from Collection, e.g.
finding the minimum or maximum number from List, calculating the sum
of all numbers from a numeric list or calculating the average of all
numbers from List.
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream()
.mapToInt((x) -> x)
.summaryStatistics();
Since these statistics operations are numeric in nature, it's essential to call
the mapToInt() method. After this, we call the summaryStatistics(),
which returns an instance of an IntSummaryStatistics.
It is this object which provides us utility method like getMin(), getMax(),
getSum() or getAverage(). 296
Java8 Features
Features of the new Date and Time API in Java
Immutable classes– In the new API all the core classes are immutable
thus thread safe. That is an improvement over the old API where thread
safety was an issue. For example if you were providing a format using the
SimpleDateFormat class, then you had to ensure thread safety using
synchronization or ThreadLocal class as SimpleDateFormat class is not
thread safe.
More intuitive and comprehensive- The classes in the new API relates
closely with the different Date and Time use cases. There are many more
utility methods provided.
Better support for time zones– If you have worked in an application
where you had to deal with dates and times in different time zones and
day light savings then you would really appreciate the support provided
for these operations in the new Date and Time API in Java.
297
Java8 Features
LocalDate in Java
LocalDate is a date in the ISO-8601 format, yyyy-MM-dd. LocalDate
does not store or represent a time or time-zone. Instead, it is just a
description of the date
LocalDate curDate = LocalDate.now();
System.out.println("Current Date - " + curDate);
If you want to obtain an instance of LocalDate from a year, month and
day.
LocalDate date = LocalDate.of(2016, 04, 3);
System.out.println("Date - " + date); // Date – 2016-04-03
LocalDate date = LocalDate.of(2016, Month.APRIL, 3);
Note
Providing wrong value like LocalDate date = LocalDate.of(2016,
Month.APRIL, 32); will result in DateTimeException. 298
Java8 Features
If you want to know whether the year is a leap year or not
System.out.println("Leap year - " + date.isLeapYear()); // Leap year –
true
If you want to go back by 50 days from the given LocalDate.
LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
System.out.println("Date - " + date);
System.out.println("New Date - " + date.minusDays(50));
//New Date – 2016-03-09
If you want to go back by 2 weeks
LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
System.out.println("Date - " + date);
System.out.println("New Date - " + date.minusWeeks(2))
//New Date – 2016-04-14
299
Java8 Features
If you want to add 1 year to the date
LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
System.out.println("Date - " + date);
System.out.println("New Date - " + date.plusYears(1));
//New Date – 2017-04-28
If you want to add 3 months to the date
LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
System.out.println("Date - " + date);
System.out.println("New Date - " + date.plusMonths(3));
//New Date – 2016-07-28

300
Java8 Features
There are methods like getDayOfWeek, getMonth, getDayOfYear to give
you the value you are looking for.
Example using getMonth()
LocalDate date = LocalDate.of(2016, Month.APRIL, 28);
System.out.println("Date - " + date);
Month month = date.getMonth();
if(month.equals(Month.APRIL)){
System.out.println("It's April");
}//It's April

301
Java8 Features
LocalTime Class in Java
1)LocalTime is a time in the ISO-8601 format, like HH:mm:ss.SSS.
2)LocalTime class does not store or represent a date or time-zone. It is a
description of the local time as seen on a wall clock. It cannot represent
an instant on the time-line without additional information such as an
offset or time-zone.
3)Time is represented to nanosecond precision. For example, the value
"14:32.30.123456789" can be stored in a LocalTime.

302
Java8 Features
If you want to Obtain an instance of the current time from the system
clock in the default time-zone.
LocalTime curTime = LocalTime.now();
System.out.println("Current Time - " + curTime);
If you want to obtain an instance of LocalTime from an hour and
minute or from an hour, minute and second or from an hour, minute,
second and nanosecond you can use
LocalTime time = LocalTime.of(16, 45, 34);
System.out.println("Time - " + time);//Time - 16:45:34
hour- the hour-of-day to represent, from 0 to 23
minute- the minute-of-hour to represent, from 0 to 59
second- the second-of-minute to represent, from 0 to 59
nanoOfSecond- the nano-of-second to represent, from 0 to 999,999,999
303
Java8 Features
If you want to subtract from the given time or add to the given time you
can use methods minusHours(), minuMinutes(), plusNanos(),
plusSeconds().
If you want to subtract 40 minutes from the given time.
LocalTime time = LocalTime.of(16, 45, 34);
System.out.println("Time - " + time);
System.out.println("New Time - " + time.minusMinutes(40));
//New Time – 16:05:34
If you want to add 12 Hours to the given time
LocalTime time = LocalTime.of(16, 45, 34);
System.out.println("Time - " + time);
System.out.println("New Time - " + time.plusHours(12));
//New Time – 04:45:34
304
Java8 Features
There are methods like getHour(), getMinute(), getNano(), getSecond()
to give you the value you are looking for.
If you want to get hour value of the given LocalTime
LocalTime time = LocalTime.of(16, 45, 34);
System.out.println("Time - " + time.getHour());
//Hour – 16

305
Java8 Features

306
Java8 Features

307
Java8 Features

308
Java8 Features

309
Java8 Features

310
Java8 Features

311
Java8 Features

312
Java8 Features

313
Java8 Features

314
Java8 Features

315
Java8 Features

316
Java8 Features

317
Java8 Features

318
Java8 Features

319
Java8 Features

320
Java8 Features

321
Java8 Features

322
Java8 Features

323
Java8 Features

324
Object Oriented Programming

325
Object Oriented Programming

326
Object Oriented Programming

327

You might also like