ECONTENT-PGCS103C-PGSE103C-MODULE1
ECONTENT-PGCS103C-PGSE103C-MODULE1
Koushik
Majumder
Maulana Abul Kalam Azad University
Designation : Associate
of Technology, West Bengal (Formerly
Professor
known as West Bengal University of
Technology)
MAIN CAMPUS: NH-34, SIMHAT,
HARINGHATA, NADIA-741249
CITY CAMPUS:BF 142,
SECTOR 1, SALT LAKE
CITY, KOLKATA, WEST
BENGAL, 700064
Department : Computer
Science and Engineering
1
M.Tech Computer Science & Engineering/Software Engineering
Object Oriented Design
PGCS103C/PGSE103C
Contact: 3L Credits: 3
Total Number of
Lectures: 48
2
CO3:Apply object oriented programming
concepts through Java for problem
solving.
Contact: 3L Credits: 3
Total Number of 48
Lectures:
Syllabus:
MODULE 1:
MODULE 2:
3
of java programming – advantages of java, byte-code & JVM, data
types, operators, control statements & loops. How to create objects and
classes. Memory management involved with object and class creation,
constructor, finalize and garbage collection, use of method overloading,
this keyword, use of objects as parameter & methods returning objects,
call by value & call by reference, static variables & methods, command
line arguments, basics of I/O operations – keyboard input using
BufferedReader & Scanner classes.
MODULE 3:
Reusability properties [8L]
MODULE 4:
Array, String, Vector and Wrapper classes [6L]
MODULE 5:
Interface and Package [4L]
MODULE 6:
4
Exception handling basics, different types of exception classes, use of
try & catch with throw, throws & finally, creation of user defined
exception classes.
MODULE 7:
Multithreading [8L]
MODULE 8:
Applet Programming [6L]
5
MODULE 2:
[8L]
MODULE 3:
[8L]
Reusability properties [8L]
MODULE 4:
[6L]
Array, String, Vector and Wrapper classes [8L]
6
Creation of multi-dimensional arrays, Creation of
vectors, Differences between arrays and vectors,
methods of the Vector class, String and
StringBuffer class, methods associated with the
String and StringBuffer class, Utility of the
wrapper classes, different types of wrapper classes
MODULE 5:
[4L]
Interface and Package [4L]
7
suspending & resuming threads.
MODULE 8:
[6L]
Applet Programming [8L]
Textbooks/References:
URL
https://ocw.mit.edu/courses/electrical-engineering-and-computer-
science/6-092-introduction-to-programming-in-java-january-iap-2010/
8
lecture-notes/
http://csvls.blogspot.in/2010/10/video-lecture-of-core-java-and-
advance.html
https://www.cse.iitb.ac.in/~nlp-ai/javalect_august2004.html
Delivery/Instructional Methodologies
9
Module1
10
BASIC, Pascal and C.
PROGRAMMING PROGRAMMING
Object oriented
approach. approach.
11
PROCEDURAL ORIENTED OBJECT ORIENTED
PROGRAMMING PROGRAMMING
Overloading is possible in
In object oriented
Object oriented
12
Advantages and Disadvantages of OOP
Advantages of OOP
OOP provides a clear modular structure for programs which makes it good for
defining abstract datatypes where implementation details are hidden and the
unit has a clearly defined interface.
OOP makes it easy to maintain and modify existing code as new objects can be
created with small differences to existing ones.
OOP provides a good framework for code libraries where supplied software
components can be easily adapted and modified by the programmer. This is
particularly useful for developing graphical user interfaces.
Concepts of OOP:
Objects
Classes
Inheritance
Polymorphism
Objects
Classes
A class is a collection of objects of similar type. Once a class is defined, any number of
objects can be created which belong to that class.
13
Data Abstraction and Encapsulation
Abstraction refers to the act of representing essential features without including the
background details or explanations. Classes use the concept of abstraction and are
defined as a list of abstract attributes. Storing data and functions in a single unit
(class) is encapsulation. Data cannot be accessible to the outside world and only those
functions which are stored in the class can access it.
Inheritance
Inheritance is the process by which objects can acquire the properties of objects of
other class. In OOP, inheritance provides reusability, like, adding additional features
to an existing class without modifying it. This is achieved by deriving a new class from
the existing one. The new class will have combined features of both the classes.
Polymorphism
Polymorphism means the ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends on the data types
used in the operation. Polymorphism is extensively used in implementing Inheritance.
14
objects and classes came into existence. The whole program is written in a
class, this class contained objects and various member functions. The first
object-oriented programming language was Simula. The main reason
behind the OOP is that we can use the real-world entities in our program.
Some famous languages like C++, Java, PHP, C#, Python, etc. are Object
oriented programming languages. OOP helps us apply real world entities
like message passing, inheritance, polymorphism, objects, classes,
abstraction, encapsulation, etc. in programming languages.
1. Real Word Entities – In OOP real world entities are used. Classes and
objects can be made of the things that are real and exist in the world.
Example of real-world entities are pen, chair, student, hospital, etc. these
examples can be considered as classes and their attributes will be
considered as their object. Let’s discuss other example in order to better
understand the classes and objects. Suppose, we take a student as class,
then objects will be student name, roll number, section, address, mobile
number, email, etc.
15
called as data hiding. In order for you to understand let’s take an example –
when you make your email id or login into an email id, you can only type
the login Id and password and view it. You do not know how or cannot see
how the data is being verified and how it is being stored? The user is
always not aware about where their id and password are going? In which
database? What is criteria for checking it? etc. Hence, it is very beneficial
practice to use this feature as it provides data security.
4. Slow Speed – Due to large size of the programs its execution speed
becomes slow. Even many coding instructions make the execution of the
program slower and effects its efficiency.
16
A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to
all objects of one type. In general, class declarations can include these
components, in order:
1. Modifiers : A class can be public or has default access (Refer this for
details).
2. Class name: The name should begin with a initial letter (capitalized
by convention).
3. Superclass(if any): The name of the class’s parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
5. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that
provides the state of the class and its objects, and methods are used to
implement the behavior of the class and its objects.
Object
It is a basic unit of Object Oriented Programming and represents the real
life entities. A typical Java program creates many objects, which as you
know, interact by invoking methods. An object consists of :
1. State : It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior : It is represented by methods of an object. It also reflects
the response of an object with other objects.
3. Identity : It gives a unique name to an object and enables one object
to interact with other objects.
Example of an object : dog
17
As we declare variables like (type name;). This notifies the compiler that
we will use name to refer to data whose type is type. With a primitive
variable, this declaration also reserves the proper amount of memory for
the variable. So for reference variable, type must be strictly a concrete
class name. In general,we can’t create objects of an abstract class or an
interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be
undetermined(null) until an object is actually created and assigned to it.
Simply declaring a reference variable does not create an object.
Initializing an object
The new operator instantiates a class by allocating memory for a new
object and returning a reference to that memory. The new operator also
invokes the class constructor.
// Class Declaration
// method 1
18
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
// method 4
public String getColor()
{
return color;
}
@Override
public String toString()
{
return("Hi my name is "+ this.getName()+
".\nMy breed,age and color are " +
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
}
19
The result of executing this statement can be illustrated as :
Note : All classes have at least one constructor. If a class does not
explicitly declare any, the Java compiler automatically provides a no-
argument constructor, also called the default constructor. This default
constructor calls the class parent’s no-argument constructor (as it contain
only one statement i.e super();), or the Object class constructor if the class
has no other parent (as Object class is parent of all classes either directly
or indirectly).
// base class
class Dog {
20
}
}
// driver class
public class Test {
public static void main(String[] args)
{
// creating objects of the class Dog
Dog ob1 = new Dog("Bravo", 4);
Dog ob2 = new Dog("Oliver", 5);
// Base class
class Example {
void message()
{
System.out.println("Hello Geeks !!");
}
}
// Driver class
class Test {
public static void main(String args[])
21
{
try {
Class c = Class.forName("Example");
Example s = (Example)c.newInstance();
s.message();
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output:
Hello Geeks !!
3. Using newInstance() method for Constructor class: It is a
reflective way to create object. By using it one can call parametrized
and private constructor. It wraps the thrown exception with an
InvocationTargetException. It is used by different frameworks- Spring,
Hibernate, Struts etc. Constructor.newInstance() method is preffered
over Class.newInstance() method.
Syntax:
Constructor constructor = ClassName.class.getConstructor();
ClassName ReferenceVariable = constructor.newInstance();
Example:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class ExampleClass {
22
public ExampleClass(String emp_name)
{
this.emp_name = emp_name;
}
// default constructor
Employee(String emp_name, int emp_id)
{
this.emp_id = emp_id;
this.emp_name = emp_name;
}
23
// driver class
public class Test {
try {
Employee ob1 = new Employee("Tom", 201);
import java.io.*;
// Base class
class Example implements java.io.Serializable {
// Default constructor
public Example(int emp_id, String emp_name)
{
this.emp_id = emp_id;
this.emp_name = emp_name;
}
}
// Driver class
class Test {
24
public static void main(String[] args)
{
Example object = new Example(1, "geeksforgeeks");
String filename = "file1.ser";
// Serialization
try {
out.close();
file1.close();
// Deserialization
try {
in.close();
file1.close();
25
Anonymous objects
Anonymous objects are the objects that are instantiated but are not stored
in a reference variable.
They are used for immediate method calling.
They will be destroyed after method calling.
They are widely used in different libraries. For example, in AWT
libraries, they are used to perform some action on capturing an
event(eg a key press).
In example below, when a key is button(referred by the btn) is
pressed, we are simply creating anonymous object of EventHandler
class for just calling handle method.
btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});
26
How are Java objects stored in memory?
In Java, all objects are dynamically allocated on Heap. This is different from
C++ where objects can be allocated memory either on Stack or on Heap.
In C++, when we allocate the object using new(), the object is allocated on
Heap, otherwise on Stack if not global or static.
In Java, when we only declare a variable of a class type, only a reference is
created (memory is not allocated for the object). To allocate memory to an
object, we must use new(). So the object is always allocated memory on
heap (See this for more details).
For example, following program fails in the compilation. Compiler gives
error “Error here because t is not initialized”.
class Test {
// class contents
void show()
{
System.out.println("Test::show() called");
}
}
// Driver Code
public static void main(String[] args)
{
Test t;
class Test {
// class contents
void show()
{
System.out.println("Test::show() called");
}
}
// Driver Code
public static void main(String[] args)
{
27
t.show(); // No error
}
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(1);
Car c2 = new Car(2);
swap(c1, c2);
System.out.println("c1.no = " + c1.no);
System.out.println("c2.no = " + c2.no);
}
}
Output:
c1.no = 2
c2.no = 1
28
This is a very common situation as a class that uses some other class may
not access members of other class. Does below solution work?
// Constructor
Car(int model, int no)
{
this.model = model;
this.no = no;
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(101, 1);
Car c2 = new Car(202, 2);
swap(c1, c2);
c1.print();
c2.print();
}
}
Output:
no = 1, model = 101
no = 2, model = 202
29
As we can see from above output, the objects are not swapped. Parameters
are passed by value in Java. So when we pass c1 and c2 to swap(), the
function swap() creates a copy of these references.
Solution is to use Wrapper Class If we create a wrapper class that
contains references of Car, we can swap cars by swapping references of
wrapper class.
// Constructor
Car(int model, int no)
{
this.model = model;
this.no = no;
}
// Constructor
CarWrapper(Car c) {this.c = c;}
}
// Driver method
public static void main(String[] args)
{
Car c1 = new Car(101, 1);
30
Car c2 = new Car(202, 2);
CarWrapper cw1 = new CarWrapper(c1);
CarWrapper cw2 = new CarWrapper(c2);
swap(cw1, cw2);
cw1.c.print();
cw2.c.print();
}
}
Output:
no = 2, model = 202
no = 1, model = 101
So a wrapper class solution works even if the user class doesn’t have
access to members of the class whose objects are to be swapped.
31
Understanding Encapsulation, Inheritance,
Polymorphism, Abstraction in OOPs
As the name suggests, Object-Oriented Programming or OOPs refers to
languages that use objects in programming. Object-oriented programming
aims to implement real-world entities like inheritance, hiding,
polymorphism etc in programming. The main aim of OOP is to bind
together the data and the functions that operate on them so that no other
part of the code can access this data except that function. In this article,
we will understand all the concepts of OOP’s along with an example.
Let’s assume that we have a bird class and we are creating a list of birds.
Let’s understand the OOP’s concepts used in this bird creation.
Inheritance: For any bird, there are a set of predefined properties which
are common for all the birds and there are a set of properties which are
specific for a particular bird. Therefore, intuitively, we can say that all the
birds inherit the common features like wings, legs, eyes, etc. Therefore, in
the object-oriented way of representing the birds, we first declare a bird
class with a set of properties which are common to all the birds. By doing
this, we can avoid declaring these common properties in every bird which
we create. Instead, we can simply inherit the bird class in all the birds
which we create. The following is an example of how the concept of
inheritance is implemented.
32
// Java program to demonstrate the
// Inheritance
For example, let’s say we have initially created a pigeon with a grey colour
by creating a constructor, any user with the instance of the object of the
pigeon can change this colour to red or black by simply referring the
attribute with “this” keyword. Therefore, in order to avoid this, we enclose
the properties in the methods. These methods are called the getters and
setters of the attributes. The idea is to simply enclose the initialization and
retrieval of the attributes in a method instead of directly referring the
attribute directly. This also gives an advantage because the setters give us
complete control in setting the value to the attribute and help us to restrict
the unnecessary changes. For example, if a pigeon is created(born) with a
grey colour, it doesn’t change until the pigeon dies. So, a user who is using
simply shouldn’t be able to change the colour as per his wish. The following
is the implementation of the getters and setters for the above Bird class.
33
}
34
parameters is overridden with different contexts, the compiler doesn’t
have any idea that the method is overridden. It simply checks if the
method exists and during the runtime, it executes the functions which
have been overridden.
In java, we can also upcast and downcast the objects. The core idea behind
this concept is also polymorphism. The idea is that the object of the bird
can have the value of the pigeon because it inheriting the features of the
bird. Therefore, a parent object can also be initialized with the child
properties if both the objects extend each other in the following way:
Bird b = new Pigeon();
35
Encapsulation in Java
Encapsulation is defined as the wrapping up of data under a single unit. It
is the mechanism that binds together code and the data it
manipulates.Other way to think about encapsulation is, it is a protective
shield that prevents the data from being accessed by the code outside this
shield.
Technically in encapsulation, the variables or data of a class is hidden
from any other class and can be accessed only through any member
function of own class in which they are declared.
As in encapsulation, the data in a class is hidden from other classes
using the data hiding concept which is achieved by making the
members or methods of class as private and the class is exposed to the
end user or the world without providing any details behind
implementation using the abstraction concept, so it is also known
as combination of data-hiding and abstraction..
Encapsulation can be achieved by: Declaring all the variables in the
class as private and writing public methods in the class to set and get
the values of variables.
36
// private variable geekName
public String getName()
{
return geekName;
}
37
System.out.println("Geek's roll: " + obj.getRoll());
Advantages of Encapsulation:
Data Hiding: The user will have no idea about the inner
implementation of the class. It will not be visible to the user that how
the class is storing values in the variables. He only knows that we are
passing the values to a setter method and variables are getting
initialized with that value.
Increased Flexibility: We can make the variables of the class as
read-only or write-only depending on our requirement. If we wish to
make the variables as read-only then we have to omit the setter
methods like setName(), setAge() etc. from the above program or if we
wish to make the variables as write-only then we have to omit the get
methods like getName(), getAge() etc. from the above program
Reusability: Encapsulation also improves the re-usability and easy
to change with new requirements.
Testing code is easy: Encapsulated code is easy to test for unit
testing.
38
Inheritance in Java
Inheritance is an important pillar of OOP(Object Oriented Programming). It
is the mechanism in java by which one class is allow to inherit the
features(fields and methods) of another class.
Important terminology:
Super Class: The class whose features are inherited is known as
super class(or a base class or a parent class).
Sub Class: The class that inherits the other class is known as sub
class(or a derived class, extended class, or child class). The subclass
can add its own fields and methods in addition to the superclass fields
and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;
39
}
// derived class
class MountainBike extends Bicycle
{
// driver class
public class Test
{
public static void main(String args[])
{
40
}
}
Output:
No of gears are 3
speed of bicycle is 100
seat height is 25
In above program, when an object of MountainBike class is created, a copy
of the all methods and fields of the superclass acquire memory in this
object. That is why, by using the object of the subclass we can also access
the members of a superclass.
Please note that during inheritance only object of subclass is created, not
the superclass. For more, refer Java Object Creation of Inherited Class.
Illustrative image of the program:
41
Types of Inheritance in Java
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
42
// Driver class
public class Main
{
public static void main(String[] args)
{
two g = new two();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
class one
{
43
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
g.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
3. Hierarchical Inheritance : In Hierarchical Inheritance, one
class serves as a superclass (base class) for more than one sub class.In
below image, the class A serves as a base class for the derived class
B,C and D.
44
// Java program to illustrate the
// concept of Hierarchical inheritance
import java.util.*;
import java.lang.*;
import java.io.*;
class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}
// Drived class
public class Main
{
public static void main(String[] args)
{
three g = new three();
g.print_geek();
45
two t = new two();
t.print_for();
g.print_geek();
}
}
Output:
Geeks
for
Geeks
4. Multiple Inheritance (Through Interfaces) : In Multiple
inheritance ,one class can have more than one superclass and inherit
features from all parent classes. Please note that Java
does not support multiple inheritance with classes. In java, we can
achieve multiple inheritance only through Interfaces. In image below,
Class C is derived from interface A and B.
interface one
{
public void print_geek();
}
interface two
{
public void print_for();
}
46
{
@Override
public void print_geek() {
System.out.println("Geeks");
}
// Drived class
public class Main
{
public static void main(String[] args)
{
child c = new child();
c.print_geek();
c.print_for();
c.print_geek();
}
}
Output:
Geeks
for
Geeks
5. Hybrid Inheritance(Through Interfaces) : It is a mix of two
or more of the above types of inheritance. Since java doesn’t support
multiple inheritance with classes, the hybrid inheritance is also not
possible with classes. In java, we can achieve hybrid inheritance only
through Interfaces.
47
Important facts about inheritance in Java
48
Abstraction in Java
Data Abstraction is the property by virtue of which only the essential
details are displayed to the user.The trivial or the non-essentials units are
not displayed to the user. Ex: A car is viewed as a car rather than its
individual components.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details.The
properties and behaviors of an object differentiate it from other objects of
similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows
that pressing the accelerators will increase the speed of car or applying
brakes will stop the car but he does not know about how on pressing the
accelerator the speed is actually increasing, he does not know about the
inner mechanism of the car or the implementation of accelerator, brakes
etc in the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can
achieve 100% abstraction using interfaces.
49
a superclass that only defines a generalization form that will be shared by
all of its subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided
design system or game simulation. The base type is “shape” and each
shape has a color, size and so on. From this, specific types of shapes are
derived(inherited)-circle, square, triangle and so on – each of which may
have additional characteristics and behaviors. For example, certain shapes
can be flipped. Some behaviors may be different, such as when you want to
calculate the area of a shape. The type hierarchy embodies both the
similarities and differences between the shapes.
50
double radius;
@Override
double area() {
return Math.PI * Math.pow(radius, 2);
}
@Override
public String toString() {
return "Circle color is " + super.color +
"and area is : " + area();
}
}
class Rectangle extends Shape{
double length;
double width;
@Override
double area() {
return length*width;
}
@Override
public String toString() {
return "Rectangle color is " + super.color +
"and area is : " + area();
}
}
public class Test
{
public static void main(String[] args)
{
Shape s1 = new Circle("Red", 2.2);
Shape s2 = new Rectangle("Yellow", 2, 4);
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}
51
Output:
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0
Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.
3. Helps to increase security of an application or program as only
important details are provided to the user.
52
Difference between Abstraction and
Encapsulation in Java with Examples
Encapsulation in Java
53
{
geekAge = newAge;
}
Abstraction in Java
54
not displayed to the user. Ex: A car is viewed as a car rather than its
individual components.
Data Abstraction may also be defined as the process of identifying only the
required characteristics of an object ignoring the irrelevant details. The
properties and behaviours of an object differentiate it from other objects of
similar type and also help in classifying/grouping the objects.
@Override
double area()
{
return Math.PI * Math.pow(radius, 2);
}
@Override
public String toString()
{
return "Circle color is "
+ super.color
+ "and area is : "
+ area();
}
}
55
class Rectangle extends Shape {
double length;
double width;
@Override
double area()
{
return length * width;
}
@Override
public String toString()
{
return "Rectangle color is "
+ super.color
+ "and area is : "
+ area();
}
}
System.out.println(s1.toString());
System.out.println(s2.toString());
}
}
Output:
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0
56
Difference between Abstraction and Encapsulation:
ABSTRACTION ENCAPSULATION
57
ABSTRACTION ENCAPSULATION
58
Message Passing in Java
What is message passing and why it is used?
Message Passing in terms of computers is communication between
processes. It is a form of communication used in object-oriented
programming as well as parallel programming. Message passing in Java is
like sending an object i.e. message from one thread to another thread. It is
used when threads do not have shared memory and are unable to share
monitors or semaphores or any other shared variables to communicate.
Suppose we consider an example of producer and consumer, likewise what
producer will produce, the consumer will be able to consume that only. We
mostly use Queue to implement communication between threads.
Example:
import java.util.Vector;
59
// initialization of queue size
static final int MAX = 7;
private Vector messages = new Vector();
@Override
public void run()
{
try {
while (true) {
Consumer(Producer p)
{
producer = p;
}
60
@Override
public void run()
{
try {
while (true) {
String message = producer.getMessage();
61
Differences between Dynamic Binding and
Message Passing in Java
Dynamic Binding: In Dynamic binding compiler doesn’t decide the
method to be called. Overriding is a perfect example of dynamic binding. In
overriding both parent and child classes have the same method. Dynamic
binding is also called Late binding.
Message Passing:
Message Passing in terms of computers is communication between
processes. It is a form of communication used in object-oriented
programming as well as parallel programming. Message passing in Java is
like sending an object i.e. message from one thread to another thread. It is
used when threads do not have shared memory and are unable to share
monitors or semaphores or any other shared variables to communicate.
Suppose we consider an example of producer and consumer, likewise what
producer will produce, the consumer will be able to consume that only. We
mostly use Queue to implement communication between threads.
62
DYNAMIC BINDING MESSAGE PASSING
objects.
a polymorphic reference
63
DYNAMIC BINDING MESSAGE PASSING
64
Polymorphism in Java
The word polymorphism means having many forms. In simple words, we
can define polymorphism as the ability of a message to be displayed in
more than one form.
Real life example of polymorphism: A person at the same time can have
different characteristic. Like a man at the same time is a father, a husband,
an employee. So the same person posses different behaviour in different
situations. This is called polymorphism.
Polymorphism is considered as one of the important features of Object
Oriented Programming. Polymorphism allows us to perform a single action
in different ways. In other words, polymorphism allows you to define one
interface and have multiple implementations. The word “poly” means many
and “morphs” means forms, So it means many forms.
In Java polymorphism is mainly divided into two types:
Compile time Polymorphism
Runtime Polymorphism
1. Compile time polymorphism: It is also known as static
polymorphism. This type of polymorphism is achieved by function
overloading or operator overloading.
65
to be overloaded. Functions can be overloaded by change in
number of arguments or/and change in type of arguments.
1. Example: By using different types of arguments
class MultiplyFun {
class Main {
public static void main(String[] args)
{
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
Output:
8
34.65
2. Example: By using different numbers of arguments
class MultiplyFun {
class Main {
public static void main(String[] args)
{
66
System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(2, 7, 3));
}
}
Output:
8
42
Operator Overloading: Java also provide option to overload
operators. For example, we can make the operator (‘+’) for string
class to concatenate two strings. We know that this is the addition
operator whose task is to add two operands. So a single operator
‘+’ when placed between integer operands, adds them and when
placed between string operands, concatenates them.
In java, Only “+” operator can be overloaded:
1. To add integers
2. To concatenate strings
Example:
class OperatorOVERDDN {
class Main {
public static void main(String[] args)
{
OperatorOVERDDN obj = new OperatorOVERDDN();
obj.operator(2, 3);
obj.operator("joe", "now");
}
}
Output:
Sum = 5
Concatinated String - joenow
Runtime polymorphism: It is also known as Dynamic Method
Dispatch. It is a process in which a function call to the overridden
method is resolved at Runtime. This type of polymorphism is achieved
by Method Overriding.
67
Method overriding, on the other hand, occurs when a derived
class has a definition for one of the member functions of the base
class. That base function is said to be overridden.
Example:
class Parent {
void Print()
{
System.out.println("parent class");
}
}
void Print()
{
System.out.println("subclass1");
}
}
void Print()
{
System.out.println("subclass2");
}
}
class TestPolymorphism3 {
public static void main(String[] args)
{
Parent a;
a = new subclass1();
a.Print();
a = new subclass2();
a.Print();
}
}
Output:
subclass1
subclass2
68
Difference between Compile-time and Run-
time Polymorphism in Java
The word polymorphism means having many forms. In simple words, we
can define polymorphism as the ability of a message to be displayed in
more than one form. In this article, we will see the difference between two
types of polymorphisms, compile time and run time.
Compile Time Polymorphism: Whenever an object is bound with their
functionality at the compile-time, this is known as the compile-time
polymorphism. At compile-time, java knows which method to call by
checking the method signatures. So this is called compile-time
polymorphism or static or early binding. Compile-time polymorphism is
achieved through method overloading. Method Overloading says you can
have more than one function with the same name in one class having a
different prototype. Function overloading is one of the ways to achieve
polymorphism but it depends on technology that which type of
polymorphism we adopt. In java, we achieve function overloading at run
time. The following is an example where compile-time polymorphism can
be observed.
// Driver code
public static void main(String args[])
{
// Here, the first addition
// function is called
System.out.println(add(2, 3));
69
Run-Time Polymorphism: Whenever an object is bound with the
functionality at run time, this is known as runtime polymorphism. The
runtime polymorphism can be achieved by method overriding. Java virtual
machine determines the proper method to call at the runtime, not at the
compile time. It is also called dynamic or late binding. Method overriding
says child class has the same method as declared in the parent class. It
means if child class provides the specific implementation of the method
that has been provided by one of its parent class then it is known as
method overriding. The following is an example where runtime
polymorphism can be observed.
// Implementing a class
class Test {
// Implementing a method
public void method()
{
System.out.println("Method 1");
}
}
// Driver code
public static void main(String args[])
{
Test test = new GFG();
test.method();
}
}
Output:
Method 2
The following table demonstrates the difference between runtime polymorphism and compile-
time polymorphism:
SR.N
70
SR.N
It is achieved by function
71
72
Important Questions
What is Java?
The differences between C++ and Java are given in the following table.
73
Goto C++ supports Java doesn't support
the goto statemen the goto statement.
t.
74
Call by and call by is no call by
reference reference. reference in java.
75
Tree new inheritance inheritance tree
tree always. always because all
classes are the child
of Object class in
java. The object
class is the root of
the inheritance tree
in java.
76
o Platform Independent: Java is a platform independent
programming language. It is different from other programming
languages like C and C++ which needs a platform to be executed.
Java comes with its platform on which its code is executed. Java
doesn't depend upon the operating system to be executed.
77
What are the main differences between the Java platform and other
platforms?
There are the following differences between the Java platform and other
platforms.
o Java is the software-based platform whereas other platforms may be
the hardware platforms or software-based platforms.
o Java is executed on the top of other hardware platforms whereas
other platforms can only have the hardware components.
What gives Java its 'write once and run anywhere' nature?
The bytecode. Java compiler converts the Java programs into the class file
(Byte Code) which is the intermediate language between source code and
machine code. This bytecode is not platform specific and can be executed
on any computer.
What is javac ?
The javac is a compiler that compiles the source code of your program and
generates bytecode. In simple words javac produces the java byte code
from the source code written *.java file. JVM executes the bytecode to run
the program.
What is class?
Path specifies the location of .exe files. Classpath specifies the location of
bytecode (.class files).
Inheritance
78
Polymorphism
Data Encapsulation
Abstraction
What is inheritance?
The process by which one class acquires the properties and functionalities
of another class is called inheritance. Inheritance brings reusability of code
in a java application. Refer: Guide to Inheritance in Java.
When a class extends more than one classes then it is called multiple
inheritance. Java doesn’t support multiple inheritance whereas C++
supports it, this is one of the difference between java and C++
79