0% found this document useful (0 votes)
1 views

ECONTENT-PGCS103C-PGSE103C-MODULE1

Uploaded by

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

ECONTENT-PGCS103C-PGSE103C-MODULE1

Uploaded by

classroomkm
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 79

LESSON PLAN Faculty : Dr.

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

Stream: M.Tech Computer Science &


Engineering/Software Engineering

1
M.Tech Computer Science & Engineering/Software Engineering
Object Oriented Design
PGCS103C/PGSE103C
Contact: 3L Credits: 3
Total Number of
Lectures: 48

Prerequisites of Object The fundamental point in learning


Oriented Programming: programming is to develop the critical skills
of formulating programmatic solutions for
real problems. It will be based on basic
knowledge of algorithms and object oriented
programming language. Once the basic skill
of writing programs using loop, methods and
arrays will be clear then the student can
develop object oriented software using class
encapsulation and inheritance.

Course Objectives : 1. To develop conceptual understanding


of Object Oriented System.

2. To understand how a real world


problem can be mapped to object
oriented problem domain.

3. To solve different industry level


problems & to learn its applications.

Course Outcome: Upon successful completion of the


course students should be able to:

CO1: Visualize a given problem scenario


in terms of classes and objects.

CO2: Acquire the knowledge about


different types of inheritance &
polymorphism, interface, package,
vector and wrapper class.

2
CO3:Apply object oriented programming
concepts through Java for problem
solving.

CO4: Acquire knowledge about threads,


thread synchronization and applets and
their life cycle.

Contact Hours and Object Oriented Design


Credit PGCS103C/PGSE103C

Contact: 3L Credits: 3

Total Number of 48
Lectures:

Syllabus:

MODULE 1:

Object oriented concepts


[4L]

Difference between OOP and other conventional programming


approaches– advantages and disadvantages. Class, object, message
passing, inheritance, encapsulation, polymorphism, dynamic binding

MODULE 2:

Basic concepts of object oriented programming


using Java [8L]

Implementation of Object oriented concepts using Java. Basic concepts

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]

Super class & subclasses including multilevel hierarchy, process of


constructor chaining, dynamic method dispatch, use of abstract classes &
methods, abstract class and abstract class hierarchy, Compile time
polymorphism and runtime polymorphism

MODULE 4:
Array, String, Vector and Wrapper classes [6L]

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:
Interface and Package [4L]

How to create interfaces, what is an interface, differences between class


and interface, Multiple inheritance using interface, using existing
packages, Advantages of packages, Creation of user defined packages,
importing packages, member access for packages, Different access
specifiers.

MODULE 6:

Exception handling [4L]

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]

Difference between process and threads, Basics of multithreading, main


thread, thread life cycle, creation of multiple threads, thread priorities,
thread synchronization, inter- thread communication, deadlocks for
threads, suspending & resuming threads.

MODULE 8:
Applet Programming [6L]

Basics of applet programming, applet life cycle, difference between


application & applet programming, parameter passing in applets,
concept of delegation event model and listener, I/O in applets.

LECTURE WITH BREAKUP NO. OF


LECTURE
S
MODULE 1:
[4L]

Object oriented concepts [4L]

Difference between OOP and other conventional


programming approaches– advantages and
disadvantages. Class, object, message passing,
inheritance, encapsulation, polymorphism,
dynamic binding

5
MODULE 2:
[8L]

Basic concepts of object oriented programming


using Java [16L]

Implementation of Object oriented concepts using


Java. Basic concepts 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:
[8L]
Reusability properties [8L]

Super class & subclasses including multilevel


hierarchy, process of constructor chaining,
dynamic method dispatch, use of abstract classes
& methods, abstract class and abstract class
hierarchy, Compile time polymorphism and
runtime polymorphism

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]

How to create interfaces, what is an interface,


differences between class and interface, Multiple
inheritance using interface, using existing
packages, Advantages of packages, Creation of
user defined packages, importing packages,
member access for packages, Different access
specifiers.
MODULE 6:
[4L]

Exception handling [4L]

Exception handling basics, different types of


exception classes, use of try & catch with throw,
throws & finally, creation of user defined
exception classes.
MODULE 7:
[8L]
Multithreading [8L]

Difference between process and threads, Basics


of multithreading, main thread, thread life cycle,
creation of multiple threads, thread priorities,
thread synchronization, inter- thread
communication, deadlocks for threads,

7
suspending & resuming threads.
MODULE 8:
[6L]
Applet Programming [8L]

Basics of applet programming, applet life cycle,


difference between application & applet
programming, parameter passing in applets,
concept of delegation event model and listener,
I/O in applets.

Textbooks/References:

1. Rambaugh, James Michael, Blaha – "Object Oriented Modelling and


Design" – Prentice Hall, India

2. Ali Bahrami – "Object Oriented System Development" – Mc Graw Hill

3. Patrick Naughton, Herbert Schildt – "The complete reference-Java2" –


TMH

4. R.K Das – "Core Java For Beginners" – VIKAS PUBLISHING

5. Deitel and Deitel – "Java How to Program" – 6th Ed. – Pearson

6. Ivor Horton's Beginning Java 2 SDK – Wrox

7. E. Balagurusamy – " Programming With Java: A Primer" – 3rd Ed. – TMH

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

SL. NO. DESCRIPTION

1 White Board and Marker

2 Study Material , Slide Show

9
Module1

Object oriented concepts


[4L]

Difference between OOP and other conventional programming


approaches– advantages and disadvantages. Class, object, message
passing, inheritance, encapsulation, polymorphism, dynamic binding

Object Oriented Concepts

Differences between Procedural and


Object Oriented Programming
Procedural Programming:
Procedural Programming can be defined as a programming model which is
derived from structured programming, based upon the concept of calling
procedure. Procedures, also known as routines, subroutines or functions,
simply consist of a series of computational steps to be carried out. During a
program’s execution, any given procedure might be called at any point,
including by other procedures or itself.
Languages used in Procedural Programming:
FORTRAN, ALGOL, COBOL,

10
BASIC, Pascal and C.

Object Oriented Programming:


Object oriented programming can be defined as a programming model
which is based upon the concept of objects. Objects contain data in the
form of attributes and code in the form of methods. In object oriented
programming, computer programs are designed using the concept of
objects that interact with real world. Object oriented programming
languages are various but the most popular ones are class-based, meaning
that objects are instances of classes, which also determine their types.
Languages used in Object Oriented Programming:
Java, C++, C#, Python,
PHP, JavaScript, Ruby, Perl,
Objective-C, Dart, Swift, Scala.

Difference between Procedural Programming and Object Oriented


Programming:
PROCEDURAL ORIENTED OBJECT ORIENTED

PROGRAMMING PROGRAMMING

In procedural programming, In object oriented

program is divided into programming, program is

small parts divided into small parts

called functions. called objects.

Object oriented

Procedural programming programming

follows top down follows bottom up

approach. approach.

There is no access specifier Object oriented

in procedural programming. programming have access

specifiers like private,

11
PROCEDURAL ORIENTED OBJECT ORIENTED

PROGRAMMING PROGRAMMING

public, protected etc.

Adding new data and Adding new data and

function is not easy. function is easy.

Procedural programming Object oriented

does not have any proper programming provides

way for hiding data so it data hiding so it is more

is less secure. secure.

Overloading is possible in

In procedural programming, object oriented

overloading is not possible. programming.

In object oriented

In procedural programming, programming, data is

function is more important more important than

than data. function.

Object oriented

Procedural programming is programming is based

based on unreal world. on real world.

Examples: C, FORTRAN, Examples: C++, Java,

Pascal, Basic etc. Python, C# etc.

12
Advantages and Disadvantages of OOP

Advantages of OOP

Object-Oriented Programming has the following advantages over conventional


approaches:

 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

 Data Abstraction and Encapsulation

 Inheritance

 Polymorphism

Objects

Objects are the basic run-time entities in an object-oriented system. Programming


problem is analyzed in terms of objects and nature of communication between them.
When a program is executed, objects interact with each other by sending messages.
Different objects can also interact with each other without knowing the details of their
data or code.

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.

Why object-oriented programming required?


At the beginning of programming language were complex and though to
use, not everyone could be a programmer. As they kept going on with their
development and inventions, they unfolded new techniques and developed
high level programming languages. The first high level programming
language was developed by Konrad Zuse named Plankalkul. Then later
FORTRAN (Formula Translation) came into being. It was available for
everyone later. Then other languages like C and PASCAL came into being.
All these languages are procedural programming languages.

There is a huge difference in procedural procedures oriented


programming Vs object-oriented programming. In procedural
languages programs contains small parts called functions whereas, in OOP
objects are used. Top down approach is followed in procedural
programming language and bottom up approach is followed in OOP. In
procedural programming operator or function overloading is not possible
but it is possible in object-oriented programming (OOP). Procedural
programming is less secure whereas OOP is more secure. Similarly, there
were many other problems that procedural programming was not able to
meet. This led to the development of Object-Oriented Programming (OOP).

Object Oriented Programming

In Object Oriented Programming also known as OOP in short, concepts of

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.

Advantages of Object-Oriented Programming (OOP)

Due to the various problems faced by the procedural languages, this


concept was introduced. Therefore, it has a number of advantages over the
procedural programming. OOP is still being widely used; new languages
also adopt these OOP concepts. Let us discuss some the advantages of the
Object-oriented programming:

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.

2. Code Reusability – Code reusability is one of the characteristics of


object-oriented programming. The feature that explains this point is
inheritance. In inheritance, the class and subclasses or parent and child
classes can be derived and its data member and member functions can be
used as such. This feature saves times and the user do not need to code
again and again, if similar features or functionality is required. Long
programs can be cut short and the lot of time can be saved.

3. Easy Management – code management becomes very easy in the


object-oriented programming. As all the code is divided into a number of
elements it becomes easy to manage. For instance, the whole program can
be termed as a class and even if it contains a number of functions are
written or coded in it, their objects can be made. This makes it easy to
manage the code, as later you can initialize the object variable and make
the function call.

4. Maintenance – Maintenance of code also becomes easy in object


oriented programming. Because of easy management of the code
maintenance also becomes easy. If the code is to be used by another
programmer, still it will not create any ambiguity of correct guiding of
coding is used.

5. Abstraction – In abstraction, only the useful data is visible to the user


and not the things that they are not required to see. Abstraction is also

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.

6. Polymorphism – It is another feature of the object oriented


programming. Polymorphism simply means that a function has many forms.
Take example of your mother, she is one person but she has different roles
to perform like being someone’s sister, wife, mother, aunt, employee, boos,
etc. Similarly, even in the programming one function can be written, this
function can be used in different forms depending on its arguments. It is
called function overloading. Just like the functions even the operator can
be overloaded. It is called operator overloading.

Disadvantages of Object Oriented Programming

Despite of having so many advantages it also has disadvantages.

1. Complex Design – Designing and proper implementation of Object


Oriented Programming (OOP) concepts is complex and burdensome.
Hence, it is difficult a many should have an extreme knowledge in order to
design and implement OOPs concepts.

2. Many skills – A programmer required many skills for a better


programming. Different skills like programming skills, designing skills,
logical thinking and problem-solving skills are needed. If a programmer
does not have an extreme knowledge about programming, then it becomes
difficult for them to code and manage.

3. Large size & Many Instructions – Programs of object-oriented


programming are of larger size in comparison with the traditional
procedural programming. Due to the larger size of the program, many
instructions are needed in order to execute the program. This make the
code complex and lengthy.

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.

Classes and Objects in Java


Classes and Objects are basic concepts of Object Oriented Programming
which revolve around the real life entities.
Class

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

Objects correspond to things found in the real world. For example, a


graphics program may have objects such as “circle”, “square”, “menu”. An
online shopping system might have objects such as “shopping cart”,
“customer”, and “product”.
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated.
All the instances share the attributes and the behavior of the class. But the
values of those attributes, i.e. the state are unique for each object. A single
class may have any number of instances.
Example :

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

public class Dog


{
// Instance Variables
String name;
String breed;
int age;
String color;

// Constructor Declaration of Class


public Dog(String name, String breed,
int age, String color)
{
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
}

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

public static void main(String[] args)


{
Dog tuffy = new Dog("tuffy","papillon", 5, "white");
System.out.println(tuffy.toString());
}
}
Output:
Hi my name is tuffy.
My breed,age and color are papillon,5,white
 This class contains a single constructor. We can recognize a
constructor because its declaration uses the same name as the class
and it has no return type. The Java compiler differentiates the
constructors based on the number and the type of the arguments. The
constructor in the Dog class takes four arguments. The following
statement provides “tuffy”,”papillon”,5,”white” as values for those
arguments:
 Dog tuffy = new Dog("tuffy","papillon",5, "white");

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

Different ways to create Objects

1. Using new keyword: It is the simplest way to create object. By


using this method, the desired constructor can be called.
Syntax:
ClassName ReferenceVariable = new ClassName();

// Java program to illustrate the


// creating and accessing objects
// using new keyword

// base class
class Dog {

// the class Dog has two fields


String dogName;
int dogAge;

// the class Dog has one constructor


Dog(String name, int age)
{
this.dogName = name;
this.dogAge = age;

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);

// accessing the object data through reference


System.out.println(ob1.dogName + ", " + ob1.dogAge);
System.out.println(ob2.dogName + ", " + ob2.dogAge);
}
}
Output:
Bravo, 4
Oliver, 5

2. Using Class.newInstance() method: It is used to create new class


dynamically. It can invoke any no-argument constructor. This method
return class Class object on which newInstance() method is called,
which will return the object of that class which is being passed as
command line argument.
Reason for different exceptions raised:-
ClassNotFoundException will occur, if the passed class doesn’t exist.
InstantiationException will occur, if the passed class doesn’t contain
default constructor as newInstance() method internally calls the
default constructor of that particular class.
IllegalAccessException will occur, if the driving class doesn’t has the
access to the definition of specified class definition.
Syntax:
ClassName ReferenceVariable =
(ClassName)
Class.forName("PackageName.ClassName").newInstance();

// Java program to demonstrate


// object creation using newInstance() method

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

// java program to demonstrate


// creation of object
// using Constructor.newInstance() method

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ConstructorExample {

// different exception is thrown


public static void main(String[] args)
throws NoSuchMethodException,
SecurityException,
InstantiationException,
IllegalAccessException,
IllegalArgumentException,
InvocationTargetException
{
Constructor constructor = ExampleClass.class
.getConstructor(String.class);
ExampleClass exampleObject = (ExampleClass)constructor
.newInstance("GeeksForGeeks");
System.out.println(exampleObject.getemp_name());
}
}

class ExampleClass {

// private variable declared


private String emp_name;

22
public ExampleClass(String emp_name)
{
this.emp_name = emp_name;
}

// get method for emp_named to access


// private variable emp_name
public String getemp_name()
{
return emp_name;
}

// set method for emp_name to access


// private variable emp_name
public void setemp_name(String emp_name)
{
this.emp_name = emp_name;
}
}
Output:
GeeksForGeeks
4. Using clone() method: It is used to make clone of an object. It is
the easiest and most efficient way to copy an object. In
code, java.lang.Cloneable interface must be implemented by the
class whose object clone is to be created. If Cloneable interface is not
implemented, clone() method
generates CloneNotSupportedException.
Syntax:

ClassName ReferenceVariable = (ClassName) ReferenceVariable.clone();


Example:

// java program to demonstrate


// object creation using clone() method

// employee class whose objects are cloned


class Employee implements Cloneable {
int emp_id;
String emp_name;

// default constructor
Employee(String emp_name, int emp_id)
{
this.emp_id = emp_id;
this.emp_name = emp_name;
}

public Object clone() throws CloneNotSupportedException


{
return super.clone();
}
}

23
// driver class
public class Test {

public static void main(String args[])


{

try {
Employee ob1 = new Employee("Tom", 201);

// Creating a new reference variable ob2


// which is pointing to the same address as ob1
Employee ob2 = (Employee)ob1.clone();

System.out.println(ob1.emp_id + ", " + ob1.emp_name);


System.out.println(ob2.emp_id + ", " + ob2.emp_name);
}
catch (CloneNotSupportedException c) {
System.out.println("Exception: " + c);
}
}
}
Output:
201, Tom
201, Tom
5. Using deserialization: To deserialize an object, first implement
a serializable interface in the class. No constructor is used to create
an object in this method.
Syntax:
ObjectInputStream in = new ObjectInputStream(new
FileInputStream(FileName));
ClassName ReferenceVariable = (ClassName) in.readObject();
Example:

// Java code to demonstrate object


// creation by deserialization

import java.io.*;

// Base class
class Example implements java.io.Serializable {

public int emp_id;


public String emp_name;

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

// Saving of object in a file


FileOutputStream file1 = new FileOutputStream(filename);
ObjectOutputStream out = new ObjectOutputStream(file1);

// Method for serialization of object


out.writeObject(object);

out.close();
file1.close();

System.out.println("Object has been serialized");


}

catch (IOException ex) {


System.out.println("IOException is caught");
}

Example object1 = null;

// Deserialization
try {

// Reading object from a file


FileInputStream file1 = new FileInputStream(filename);
ObjectInputStream in = new ObjectInputStream(file1);

// Method for deserialization of object


object1 = (Example)in.readObject();

in.close();
file1.close();

System.out.println("Object has been deserialized");


System.out.println("Employee ID = " + object1.emp_id);
System.out.println("Employee Name = " + object1.emp_name);
}

catch (IOException ex) {


System.out.println("IOException is caught");
}

catch (ClassNotFoundException ex) {


System.out.println("ClassNotFoundException is caught");
}
}
}

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!");
 }
});

Differences between Objects and Classes

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");
}
}

public class Main {

// Driver Code
public static void main(String[] args)
{
Test t;

// Error here because t


// is not initialzed
t.show();
}
}
Allocating memory using new() makes above program work.

class Test {

// class contents
void show()
{
System.out.println("Test::show() called");
}
}

public class Main {

// Driver Code
public static void main(String[] args)
{

// all objects are dynamically


// allocated
Test t = new Test();

27
t.show(); // No error
}
}

How to swap or exchange objects in Java?


How to swap objects in Java?
Let’s say we have a class called “Car” with some attributes. And we create
two objects of Car, say car1 and car2, how to exchange the data of car1
and car2?
A Simple Solution is to swap members. For example, if the class Car
has only one integer attribute say “no” (car number), we can swap cars by
simply swapping the members of two cars.

// A Java program to demonstrate that we can swap two


// objects be swapping members.

// A car with number class Car


class Car
{
int no;
Car(int no) { this.no = no; }
}

// A class that uses Car objects


class Main
{
// To swap c1 and c2
public static void swap(Car c1, Car c2)
{
int temp = c1.no;
c1.no = c2.no;
c2.no = temp;
}

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

What if we don’t know members of Car?


The above solution worked as we knew that there is one member “no” in
Car. What if we don’t know members of Car or the member list is too big.

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?

// A Java program to demonstrate that simply swapping


// object references doesn't work

// A car with number and name


class Car
{
int model, no;

// Constructor
Car(int model, int no)
{
this.model = model;
this.no = no;
}

// Utility method to print Car


void print()
{
System.out.println("no = " + no +
", model = " + model);
}
}

// A class that uses Car


class Main
{
// swap() doesn't swap c1 and c2
public static void swap(Car c1, Car c2)
{
Car temp = c1;
c1 = c2;
c2 = temp;
}

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

// A Java program to demonstrate that we can use wrapper


// classes to swap to objects

// A car with model and no.


class Car
{
int model, no;

// Constructor
Car(int model, int no)
{
this.model = model;
this.no = no;
}

// Utility method to print object details


void print()
{
System.out.println("no = " + no +
", model = " + model);
}
}

// A Wrapper over class that is used for swapping


class CarWrapper
{
Car c;

// Constructor
CarWrapper(Car c) {this.c = c;}
}

// A Class that use Car and swaps objects of Car


// using CarWrapper
class Main
{
// This method swaps car objects in wrappers
// cw1 and cw2
public static void swap(CarWrapper cw1,
CarWrapper cw2)
{
Car temp = cw1.c;
cw1.c = cw2.c;
cw2.c = temp;
}

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

// Java program to demonstrate


// the bird class

// Implementing the bird class


public class Bird {

// Few properties which


// define the bird
String color;
int legs;

// Few operations which the


// bird performs
public void eat()
{
System.out.println(
"This bird has eaten");
}

public void fly()


{
System.outp.println(
"This bird is flying");
}
}
After the bird class is implemented, if we wish to create a pigeon, then we
simply inherit the above Bird class.

32
// Java program to demonstrate the
// Inheritance

// Creating the Pigeon class which


// extends the bird class
public class Pigeon extends Bird {

// Overriding the fly method


// which makes this pigeon fly
public void fly()
{
System.out.println(
"Pigeon flys!!!!");
}
}
Encapsulation: Now, we have defined the properties of the bird class and
the attributes which the birds have like colour, wings, legs can be
initialized by creating an object of the bird class. However, if we simply are
able to change the properties of the bird class just by the reference of the
object, then the attributes lose the information by which it was initially
initialized.

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.

// Java program to demonstrate


// the bird class

// Implementing the bird class


public class Bird {

// Few properties which


// define the bird
String color;
int legs;

// Implementing the getters and


// setters for the color and legs.

public void setColor(String color)


{
this.color = color;

33
}

public String getColor()


{
return this.color;
}

public void setLegs(String legs)


{
this.legs = legs;
}

public String getLegs()


{
return this.legs;
}

// Few operations which the


// bird performs
public void eat()
{
System.out.println(
"This bird has eaten");
}

public void fly()


{
System.outp.println(
"This bird is flying");
}
}

Polymorphism: The word polymorphism is made of two words poly and


morph, where poly means many and morphs means forms. In
programming, polymorphism is a feature that allows one interface to be
used for a general class of actions. In the above concept of a bird and
pigeon, a pigeon is inherently a bird. And also, if the birds are further
categorized into multiple categories like flying birds, flightless birds, etc.
the pigeon also fits into the flying bird’s category. And also, if the animal
class is further categorized into plant-eating animals and meat-eating
animals, the pigeon again comes into the plant-eating animal’s category.
Therefore, the idea of polymorphism is the ability of the same object to
take multiple forms. There are two types of polymorphism:
1. Compile Time Polymorphism: It is also known as static
polymorphism. This type of polymorphism is achieved by function
overloading or operator overloading. It occurs when we define multiple
methods with different signatures and the compiler knows which
method needs to be executed based on the method signatures.
2. Run Time 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. When the same method with the same

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();

Abstraction: Abstraction in general means hiding. In the above scenario of


the bird and pigeon, let’s say there is a user who wants to see pigeon fly.
The user is simply interested in seeing the pigeon fly but not interested in
how the bird is actually flying. Therefore, in the above scenario where the
user wishes to make it fly, he will simply call the fly method by
using pigeon.fly() where the pigeon is the object of the bird pigeon.
Therefore, abstraction means the art of representing the essential features
without concerning about the background details. In Java, the abstraction
is implemented through the use of interface and abstract classes. We can
achieve complete abstraction with the use of Interface whereas a partial or
a complete abstraction can be achieved with the use of abstract classes.
The reason why abstraction is considered as one of the important concepts
is:
1. It reduces the complexity of viewing 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.

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.

// Java program to demonstrate encapsulation


public class Encapsulate
{
// private variables declared
// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;

// get method for age to access


// private variable geekAge
public int getAge()
{
return geekAge;
}

// get method for name to access

36
// private variable geekName
public String getName()
{
return geekName;
}

// get method for roll to access


// private variable geekRoll
public int getRoll()
{
return geekRoll;
}

// set method for age to access


// private variable geekage
public void setAge( int newAge)
{
geekAge = newAge;
}

// set method for name to access


// private variable geekName
public void setName(String newName)
{
geekName = newName;
}

// set method for roll to access


// private variable geekRoll
public void setRoll( int newRoll)
{
geekRoll = newRoll;
}
}
In the above program the class EncapsulateDemo is encapsulated as the
variables are declared as private. The get methods like getAge() ,
getName() , getRoll() are set as public, these methods are used to access
these variables. The setter methods like setName(), setAge(), setRoll() are
also declared as public and are used to set the values of the variables.
The program to access variables of the class EncapsulateDemo is shown
below:

public class TestEncapsulation


{
public static void main (String[] args)
{
Encapsulate obj = new Encapsulate();

// setting values of the variables


obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);

// Displaying values of the variables


System.out.println("Geek's name: " + obj.getName());
System.out.println("Geek's age: " + obj.getAge());

37
System.out.println("Geek's roll: " + obj.getRoll());

// Direct access of geekRoll is not possible


// due to encapsulation
// System.out.println("Geek's roll: " + obj.geekName);
}
}
Output:

Geek's name: Harsh


Geek's age: 19
Geek's roll: 51

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.

How to use inheritance in Java


The keyword used for inheritance is extends.
Syntax :
class derived-class extends base-class
{
//methods and fields
}
Example: In below example of inheritance, class Bicycle is a base class,
class MountainBike is a derived class which extends Bicycle class and class
Test is a driver class to run program.

//Java program to illustrate the


// concept of inheritance

// base class
class Bicycle
{
// the Bicycle class has two fields
public int gear;
public int speed;

// the Bicycle class has one constructor


public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}

// the Bicycle class has three methods


public void applyBrake(int decrement)
{
speed -= decrement;

39
}

public void speedUp(int increment)


{
speed += increment;
}

// toString() method to print info of Bicycle


public String toString()
{
return("No of gears are "+gear
+"\n"
+ "speed of bicycle is "+speed);
}
}

// derived class
class MountainBike extends Bicycle
{

// the MountainBike subclass adds one more field


public int seatHeight;

// the MountainBike subclass has one constructor


public MountainBike(int gear,int speed,
int startHeight)
{
// invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// the MountainBike subclass adds one more method


public void setHeight(int newValue)
{
seatHeight = newValue;
}

// overriding toString() method


// of Bicycle to print more info
@Override
public String toString()
{
return (super.toString()+
"\nseat height is "+seatHeight);
}

// driver class
public class Test
{
public static void main(String args[])
{

MountainBike mb = new MountainBike(3, 100, 25);


System.out.println(mb.toString());

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:

In practice, inheritance and polymorphism are used together in java to


achieve fast performance and readability of code.

41
Types of Inheritance in Java

Below are the different types of inheritance which is supported by Java.


1. Single Inheritance : In single inheritance, subclasses inherit
the features of one superclass. In image below, the class A serves as a
base class for the derived class B.

//Java program to illustrate the


// concept of single inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


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

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

2. Multilevel Inheritance : In Multilevel Inheritance, a derived


class will be inheriting a base class and as well as the derived class
also act as the base class to other class. In below image, the class A
serves as a base class for the derived class B, which in turn serves as a
base class for the derived class C. In Java, a class cannot directly
access the grandparent’s members.

// Java program to illustrate the


// concept of Multilevel inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

class one
{

43
public void print_geek()
{
System.out.println("Geeks");
}
}

class two extends one


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

class three extends two


{
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");
}
}

class two extends one


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

class three extends one


{
/*............*/
}

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

// Java program to illustrate the


// concept of Multiple inheritance
import java.util.*;
import java.lang.*;
import java.io.*;

interface one
{
public void print_geek();
}

interface two
{
public void print_for();
}

interface three extends one,two


{
public void print_geek();
}
class child implements three

46
{
@Override
public void print_geek() {
System.out.println("Geeks");
}

public void print_for()


{
System.out.println("for");
}
}

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

 Default superclass: Except Object class, which has no superclass,


every class has one and only one direct superclass (single inheritance).
In the absence of any other explicit superclass, every class is implicitly
a subclass of Object class.
 Superclass can only be one: A superclass can have any number of
subclasses. But a subclass can have only one superclass. This is
because Java does not support multiple inheritance with classes.
Although with interfaces, multiple inheritance is supported by java.
 Inheriting Constructors: A subclass inherits all the members
(fields, methods, and nested classes) from its superclass. Constructors
are not members, so they are not inherited by subclasses, but the
constructor of the superclass can be invoked from the subclass.
 Private member inheritance: A subclass does not inherit the
private members of its parent class. However, if the superclass has
public or protected methods(like getters and setters) for accessing its
private fields, these can also be used by the subclass.

What all can be done in a Subclass?


In sub-classes we can inherit members as is, replace them, hide them, or
supplement them with new members:
 The inherited fields can be used directly, just like any other fields.
 We can declare new fields in the subclass that are not in the
superclass.
 The inherited methods can be used directly as they are.
 We can write a new instance method in the subclass that has the
same signature as the one in the superclass, thus overriding it (as in
example above, toString() method is overridden).
 We can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.
 We can declare new methods in the subclass that are not in the
superclass.
 We can write a subclass constructor that invokes the constructor of
the superclass, either implicitly or by using the keyword super.

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.

Abstract classes and Abstract methods :

1. An abstract class is a class that is declared with abstract keyword.


2. An abstract method is a method that is declared without an
implementation.
3. An abstract class may or may not have all abstract methods. Some of
them can be concrete methods
4. A method defined abstract must always be redefined in the
subclass,thus making overriding compulsory OR either make subclass
itself abstract.
5. Any class that contains one or more abstract methods must also be
declared with abstract keyword.
6. There can be no object of an abstract class.That is, an abstract class
can not be directly instantiated with the new operator.
7. An abstract class can have parametrized constructors and default
constructor is always present in an abstract class.

When to use abstract classes and abstract methods with an example

There are situations in which we will want to define a superclass that


declares the structure of a given abstraction without providing a complete
implementation of every method. That is, sometimes we will want to create

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.

// Java program to illustrate the


// concept of Abstraction
abstract class Shape
{
String color;

// these are abstract methods


abstract double area();
public abstract String toString();

// abstract class can have constructor


public Shape(String color) {
System.out.println("Shape constructor called");
this.color = color;
}

// this is a concrete method


public String getColor() {
return color;
}
}
class Circle extends Shape
{

50
double radius;

public Circle(String color,double radius) {

// calling Shape constructor


super(color);
System.out.println("Circle constructor called");
this.radius = 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;

public Rectangle(String color,double length,double width) {


// calling Shape constructor
super(color);
System.out.println("Rectangle constructor called");
this.length = length;
this.width = 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

Encapsulation vs Data Abstraction


1. Encapsulation is data hiding(information hiding) while Abstraction is
detail hiding(implementation hiding).
2. While encapsulation groups together data and methods that act upon
the data, data abstraction deals with exposing the interface to the user
and hiding the details of implementation.

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

Encapsulation is defined as the wrapping up of data under a single unit. It


is the mechanism that binds together code and the data it manipulates.
Another way to think about encapsulation is, 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, so it is
also known as data-hiding.
Encapsulation can be achieved by Declaring all the variables in the class as
private and writing public methods in the class to set and get the values of
variables.

// Java program to demonstrate encapsulation

public class Encapsulate {

// private variables declared


// these can only be accessed by
// public methods of class
private String geekName;
private int geekRoll;
private int geekAge;

// get method for age to access


// private variable geekAge
public int getAge()
{
return geekAge;
}

// get method for name to access


// private variable geekName
public String getName()
{
return geekName;
}

// get method for roll to access


// private variable geekRoll
public int getRoll()
{
return geekRoll;
}

// set method for age to access


// private variable geekage
public void setAge(int newAge)

53
{
geekAge = newAge;
}

// set method for name to access


// private variable geekName
public void setName(String newName)
{
geekName = newName;
}

// set method for roll to access


// private variable geekRoll
public void setRoll(int newRoll)
{
geekRoll = newRoll;
}
}

// Class to access variables


// of the class Encapsulate
class TestEncapsulation {
public static void main(String[] args)
{
Encapsulate obj = new Encapsulate();

// setting values of the variables


obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);

// Displaying values of the variables


System.out.println("Geek's name: " + obj.getName());
System.out.println("Geek's age: " + obj.getAge());
System.out.println("Geek's roll: " + obj.getRoll());

// Direct access of geekRoll is not possible


// due to encapsulation
// System.out.println("Geek's roll: " + obj.geekName);
}
}
Output:

Geek's name: Harsh


Geek's age: 19
Geek's roll: 51

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

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.

// Java program to illustrate the concept of Abstraction

abstract class Shape {


String color;

// these are abstract methods


abstract double area();
public abstract String toString();

// abstract class can have a constructor


public Shape(String color)
{
System.out.println("Shape constructor called");
this.color = color;
}

// this is a concrete method


public String getColor()
{
return color;
}
}
class Circle extends Shape {
double radius;

public Circle(String color, double radius)


{

// calling Shape constructor


super(color);
System.out.println("Circle constructor called");
this.radius = 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();
}
}

55
class Rectangle extends Shape {

double length;
double width;

public Rectangle(String color,


double length,
double width)
{

// calling Shape constructor


super(color);
System.out.println("Rectangle constructor called");
this.length = length;
this.width = 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());
}
}
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

Abstraction is the process or

method of gaining the While encapsulation is the process or

information. method to contain the information.

In abstraction, problems are

solved at the design or While in encapsulation, problems are

interface level. solved at the implementation level.

Whereas encapsulation is a method to

Abstraction is the method of hide the data in a single entity or unit

hiding the unwanted along with a method to protect

information. information from outside.

We can implement Whereas encapsulation can be

abstraction using abstract implemented using by access modifier

class and interfaces. i.e. private, protected and public.

In abstraction, While in encapsulation, the data is

implementation complexities hidden using methods of getters and

57
ABSTRACTION ENCAPSULATION

are hidden using abstract

classes and interfaces. setters.

The objects that help to

perform abstraction are Whereas the objects that result in

encapsulated. encapsulation need not be abstracted.

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.

In the example explained below, we will be using vector(queue) to store the


messages, 7 at a time and after that producer will wait for the consumer
until the queue is empty.
In Producer there are two synchronized methods putMessage() which will
call form run() method of Producer and add message in Vector
whereas getMessage() extracts the message from the queue for the
consumer.
Using message passing simplifies the producer-consumer problem as they
don’t have to reference each other directly but only communicate via a
queue.

Example:

import java.util.Vector;

class Producer extends Thread {

59
// initialization of queue size
static final int MAX = 7;
private Vector messages = new Vector();

@Override
public void run()
{
try {
while (true) {

// producing a message to send to the consumer


putMessage();

// producer goes to sleep when the queue is full


sleep(1000);
}
}
catch (InterruptedException e) {
}
}

private synchronized void putMessage()


throws InterruptedException
{

// checks whether the queue is full or not


while (messages.size() == MAX)

// waits for the queue to get empty


wait();

// then again adds element or messages


messages.addElement(new java.util.Date().toString());
notify();
}

public synchronized String getMessage()


throws InterruptedException
{
notify();
while (messages.size() == 0)
wait();
String message = (String)messages.firstElement();

// extracts the message from the queue


messages.removeElement(message);
return message;
}
}

class Consumer extends Thread {


Producer producer;

Consumer(Producer p)
{
producer = p;
}

60
@Override
public void run()
{
try {
while (true) {
String message = producer.getMessage();

// sends a reply to producer got a message


System.out.println("Got message: " + message);
sleep(2000);
}
}
catch (InterruptedException e) {
}
}

public static void main(String args[])


{
Producer producer = new Producer();
producer.start();
new Consumer(producer).start();
}
}
Output:
Got message: Thu May 09 06:57:53 UTC 2019
Got message: Thu May 09 06:57:54 UTC 2019
Got message: Thu May 09 06:57:55 UTC 2019
Got message: Thu May 09 06:57:56 UTC 2019
Got message: Thu May 09 06:57:57 UTC 2019
Got message: Thu May 09 06:57:58 UTC 2019
Got message: Thu May 09 06:57:59 UTC 2019
Got message: Thu May 09 06:58:00 UTC 2019

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.

Differences between Dynamic Binding and Message Passing:


DYNAMIC BINDING MESSAGE PASSING

Binding refers to the linking of

a procedure call to the code to The process of programming in which

be executed in response to the communication is involved is known

call. as message passing.

It allows execution of different

codes using the same object at It allows developing communication

runtime. between objects.

The usage of Dynamic binding It involves three basic steps. They

to allow executing different are:

codes using the same object at  Creating classes

runtime.  Creating objects

62
DYNAMIC BINDING MESSAGE PASSING

 Establishing communication among

objects.

It is the method of linking a

procedure call to the relevant Message passing is the method of

code that will be executed exchanging message between objects

only at runtime. in Object Oriented Programming.

The code associated with the

procedure is not known until

the program is executed. This Message passing involves name of

process is known as late the objects, the name of the function

binding. and the information to be sent.

A function call associated with

a polymorphic reference

depends on the dynamic type Communication with an object is

of that reference. feasible as long as it is alive.

A message for an object is a request

In dynamic binding, only at for execution of a procedure, and

run time the code matching therefore invoke a function in the

the object under current receiving object that generates the

reference will be called. desired result.

63
DYNAMIC BINDING MESSAGE PASSING

In short, dynamic binding Message passing occurs between two

occurs during runtime. processes.

Dynamic binding is also

known as dynamic dispatch,

late binding or run-time Message passing is also known as

binding. message exchanging.

Object based programming

does not support dynamic Object based programming support

binding. message passing.

Object oriented programming Object oriented programming also

support dynamic binding. support 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.

 Method Overloading: When there are multiple functions with


same name but different parameters then these functions are said

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

// Java program for Method overloading

class MultiplyFun {

// Method with 2 parameter


static int Multiply(int a, int b)
{
return a * b;
}

// Method with the same name but 2 double parameter


static double Multiply(double a, double b)
{
return a * b;
}
}

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

// Java program for Method overloading

class MultiplyFun {

// Method with 2 parameter


static int Multiply(int a, int b)
{
return a * b;
}

// Method with the same name but 3 parameter


static int Multiply(int a, int b, int c)
{
return a * b * c;
}
}

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:

// Java program for Operator overloading

class OperatorOVERDDN {

void operator(String str1, String str2)


{
String s = str1 + str2;
System.out.println("Concatinated String - "
+ s);
}

void operator(int a, int b)


{
int c = a + b;
System.out.println("Sum = " + c);
}
}

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:

// Java program for Method overridding

class Parent {

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

class subclass1 extends Parent {

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

class subclass2 extends Parent {

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.

// Java program to demonstrate


// compile-time polymorphism
public class GFG {

// First addition function


public static int add(int a, int b)
{
return a + b;
}

// Second addition function


public static double add(
double a, double b)
{
return a + b;
}

// Driver code
public static void main(String args[])
{
// Here, the first addition
// function is called
System.out.println(add(2, 3));

// Here, the second addition


// function is called
System.out.println(add(2.0, 3.0));
}
}
Output:
5
5.0

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.

// Java program to demonstrate


// runtime polymorphism

// Implementing a class
class Test {

// Implementing a method
public void method()
{
System.out.println("Method 1");
}
}

// Defining a child class


public class GFG extends Test {

// Overriding the parent method


public void method()
{
System.out.println("Method 2");
}

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

O COMPILE TIME POLYMORPHISM RUN TIME POLYMORPHISM

1 In Compile time Polymorphism, In Run time Polymorphism,

the call is resolved by the the call is not resolved by

70
SR.N

O COMPILE TIME POLYMORPHISM RUN TIME POLYMORPHISM

compiler. the compiler.

It is also known as Static binding, It is also known as Dynamic

Early binding and overloading as binding, Late binding and

2 well. overriding as well.

Method overloading is the Method overriding is the

compile-time polymorphism runtime polymorphism

where more than one methods having same method with

share the same name with same parameters or

different parameters or signature signature, but associated in

3 and different return type. different classes.

It is achieved by function

overloading and operator It is achieved by virtual

4 overloading. functions and pointers.

It provides slow execution as

It provides fast execution compare to early binding

because the method that needs because the method that

to be executed is known early at needs to be executed is

5 the compile time. known at the runtime.

Compile time polymorphism is Run time polymorphism is

less flexible as all things execute more flexible as all things

6 at compile time. execute at run time.

71
72
Important Questions

What is Java?

Java is the high-level, object-oriented, robust, secure programming


language, platform-independent, high performance, Multithreaded, and
portable programming language. It was developed by James Gosling in
June 1991. It can also be known as the platform as it provides its own JRE
and API.

What are the differences between C++ and Java?

The differences between C++ and Java are given in the following table.

Comparison C++ Java


Index

Platform- C++ is platform- Java is platform-


independen dependent. independent.
t

Mainly used C++ is mainly Java is mainly used


for used for system for application
programming. programming. It is
widely used in
window, web-based,
enterprise and
mobile applications.

Design Goal C++ was Java was designed


designed for and created as an
systems and interpreter for
applications printing systems
programming. It but later extended
was an extension as a support
of C network computing.
programming It was designed
language. with a goal of being
easy to use and
accessible to a
broader audience.

73
Goto C++ supports Java doesn't support
the goto statemen the goto statement.
t.

Multiple C++ supports Java doesn't support


inheritance multiple multiple inheritance
inheritance. through class. It
can be achieved
by interfaces in
java.

Operator C++ Java doesn't support


Overloading supports operator operator
overloading. overloading.

Pointers C++ Java supports


supports pointers. pointer internally.
You can write However, you can't
pointer program write the pointer
in C++. program in java. It
means java has
restricted pointer
support in Java.

Compiler C++ uses Java uses compiler


and compiler only. C+ and interpreter
Interpreter + is compiled and both. Java source
run using the code is converted
compiler which into bytecode at
converts source compilation time.
code into The interpreter
machine code so, executes this
C++ is platform bytecode at runtime
dependent. and produces
output. Java is
interpreted that is
why it is platform
independent.

Call by C++ supports Java supports call


Value and both call by value by value only. There

74
Call by and call by is no call by
reference reference. reference in java.

Structure C++ supports Java doesn't support


and Union structures and structures and
unions. unions.

Thread C++ doesn't have Java has built-


Support built-in support in thread support.
for threads. It
relies on third-
party libraries for
thread support.

Documentat C++ doesn't Java supports


ion support documentation
comment documentation comment (/** ... */)
comment. to create
documentation for
java source code.

Virtual C++ supports Java has no virtual


Keyword virtual keyword keyword. We can
so that we can override all non-
decide whether or static methods by
not override a default. In other
function. words, non-static
methods are virtual
by default.

unsigned C++ doesn't Java supports


right shift support >>> unsigned right shift
>>> operator. >>> operator that
fills zero at the top
for the negative
numbers. For
positive numbers, it
works same like >>
operator.

Inheritance C++ creates a Java uses a single

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.

Hardware C++ is nearer to Java is not so


hardware. interactive with
hardware.

Object- C++ is an object- Java is also


oriented oriented an object-oriented l
language. anguage. However,
However, in C everything (except
language, single fundamental types)
root hierarchy is is an object in Java.
not possible. It is a single root
hierarchy as
everything gets
derived from
java.lang.Object.

List the features of Java Programming language.

There are the following features in Java Programming Language.


o Simple: Java is easy to learn. The syntax of Java is based on C++
which makes easier to write the program in it.

o Object-Oriented: Java follows the object-oriented paradigm which


allows us to maintain our code as the combination of different type of
objects that incorporates both data and behavior.

o Portable: Java supports read-once-write-anywhere approach. We can


execute the Java program on every machine. Java program (.java) is
converted to bytecode (.class) which can be easily run on every
machine.

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.

o Secured: Java is secured because it doesn't use explicit pointers.


Java also provides the concept of ByteCode and Exception handling
which makes it more secured.

o Robust: Java is a strong programming language as it uses strong


memory management. The concepts like Automatic garbage
collection, Exception handling, etc. make it more robust.

o Architecture Neutral: Java is architectural neutral as it is not


dependent on the architecture. In C, the size of data types may vary
according to the architecture (32 bit or 64 bit) which doesn't exist in
Java.

o Interpreted: Java uses the Just-in-time (JIT) interpreter along with


the compiler for the program execution.

o High Performance: Java is faster than other traditional interpreted


programming languages because Java bytecode is "close" to native
code. It is still a little bit slower than a compiled language (e.g., C+
+).

o Multithreaded: We can write Java programs that deal with many


tasks at once by defining multiple threads. The main advantage of
multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-
media, Web applications, etc.

o Distributed: Java is distributed because it facilitates users to create


distributed applications in Java. RMI and EJB are used for creating
distributed applications. This feature of Java makes us able to access
files by calling the methods from any machine on the internet.

o Dynamic: Java is a dynamic language. It supports dynamic loading of


classes. It means classes are loaded on demand. It also supports
functions from its native languages, i.e., C and C++.

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?

A class is a blueprint or template or prototype from which you can create


the object of that class. A class has set of properties and methods that are
common to its objects.

What is the base class of all classes?

java.lang.Object is the base class (super class) of all classes in java.

What is a path and classPath in Java?

Path specifies the location of .exe files. Classpath specifies the location of
bytecode (.class files).

Four main principles of OOPS Concepts?

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

Does Java support Multiple Inheritance?

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

What is Polymorphism and what are the types of it?

Polymorphism is the ability of an object to take many forms. The most


common use of polymorphism in OOPs is to have more than one method
with the same name in a single class. There are two types of polymorphism:
static polymorphism and dynamic polymorphism.

79

You might also like