SlideShare a Scribd company logo
1 of 25
Download to read offline
Cloud IT Solution Page 399
Object Oriented Programming System
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the
software development and maintenance by providing some concepts:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Advantage of OOPs over Procedure-oriented programming language
 OOPs makes development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.
 OOPs provide data hiding whereas in Procedure-oriented programming language a global
data can be accessed from anywhere.
 OOPs provide ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming
language.
Object
 Object is a real world entity.
 Object is a run time entity.
 Object is an entity which has state and behavior.
 Object is an instance of a class.
 It can be physical or logical (tangible and intangible). The example of intangible object is
banking system.
 Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance (result) of a class.
Object Oriented Programming
Cloud IT Solution Page 400
Characteristics
 State: represents data (value) of an object.
 Behavior: represents the behavior (functionality) of an object such as deposit, withdraw
etc.
 Identity: Object identity is typically implemented via a unique ID. The value of the ID is
not visible to the external user. But, it is used internally by the JVM to identify each object
uniquely.
Code Example
class Student{
int id; //field or data member or instance variable
String name;
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through
reference variable
System.out.println(s1.name);
}
}
Class
 Collection of objects is called class. It is a logical entity.
 A class in Java can contain-
 fields
 methods
 constructors
 blocks
 nested class and interface
Syntax to declare a class
class <class_name>{
field;
method;
}
Method
 In java, a method is like function i.e. used to expose behavior of an object.
 Advantage of Method
 Code Reusability
 Code Optimization
Instance variable
 A variable which is created inside the class but outside the method is known as instance
variable. Instance variable doesn't get memory at compile time. It gets memory at run time
when object (instance) is created. That is why, it is known as instance variable
Cloud IT Solution Page 401
Inheritance
 When one object acquires all the properties and behaviors of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
 Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance?
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Why multiple inheritances is not supported in java?
 To reduce the complexity and simplify the language, multiple inheritances is not supported
in java.
 Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object, there
will be ambiguity to call method of A or B class.
 Since compile time errors are better than runtime errors, java renders compile time error if
you inherit 2 classes. So whether you have same method or different, there will be compile
time error now.
Employee
Salary:float
Programmer
Bonus:int
Cloud IT Solution Page 402
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Polymorphism
 When one task is performed by different ways i.e. known as polymorphism.
For example: to convince the customer differently, to draw something e.g. shape or rectangle
etc.
 In java, we use method overloading and method overriding to achieve polymorphism.
 Another example can be to speak something e.g. cat speaks meow, dog barks woof etc.
Features
 Method Overloading.
 Method overwriting.
Method Overloading
 If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
 If we have to perform only one operation, having same name of the methods increases the
readability of the program
Advantage of method overloading
 Method overloading increases the readability of the program.
Different ways to overload the method
 There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
Cloud IT Solution Page 403
Method Overloading: changing no. of arguments
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Method Overloading: changing data type of arguments
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Why Method Overloading is not possible by changing the return type of method only ?
In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:
class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Can we overload java main () method?
Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:
class TestOverloading4{
public static void main(String[]
args){System.out.println("main with String[]");}
public static void main(String
args){System.out.println("main with String");}
Cloud IT Solution Page 404
public static void main(){System.out.println("main
without args");}
}
Output: main with String[]
Method Overriding
 If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
 In other words, if subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
 Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
 method must have same name as in the parent class
 method must have same parameter as in the parent class.
 must be IS-A relationship (inheritance).
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
Bank
getRateOfInerest():float
SBI
getRateOfInerest():float
ICICI
getRateOfInerest():float
ICICI
getRateOfInerest():float
extends
Cloud IT Solution Page 405
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest:
"+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest:
"+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest:
"+b.getRateOfInterest());
}
Can we override static method?
 No, static method cannot be overridden. It can be proved by runtime polymorphism, so
we will learn it later.
Why we cannot override static method?
 Because static method is bound with class whereas instance method is bound with object.
Static belongs to class area and instance belongs to heap area.
Can we override java main method?
 No, because main is a static method.
Method Overloading Vs. Method Overriding
Method Overloading Method Overriding
Method overloading is used to increase the
readability of the program.
Method overriding is used to provide the
specific implementation of the method that is
already provided by its super class.
Method overloading is performed within class. Method overriding occurs in two classes that
have IS-A (inheritance) relationship.
In case of method overloading, parameter must be
different.
In case of method overriding, parameter must
be same.
Method overloading is the example of compile time
polymorphism.
Method overriding is the example of run time
polymorphism.
In java, method overloading can't be performed by
changing return type of the method only. Return type
can be same or different in method overloading. But
you must have to change the parameter.
Return type must be same or covariant in
method overriding.
Cloud IT Solution Page 406
Abstraction
 Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing.
 In java, we use abstract class and interface to achieve abstraction
Code Example
class Employee extends Person {
private String empCode;
public String getEmpCode() {
return empCode;
}
public void setEmpCode(String empCode) {
this.empCode = empCode;
}
}
abstract class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Main{
public static void main(String args[]){
//Instiating an abstract class gives compile time
error
//Person p = new Person() ;
//This reference variable can acess only those method which
are overridden
Person person = new Employee();
person.setName("Jatin Kansagara");
System.out.println(person.getName());
}
}
Interface
 An interface in java is a blueprint of a class. It has static constants and abstract methods.
 The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and
multiple inheritance in Java
 Java Interface also represents IS-A relationship.
Why use Java interface
 There are mainly three reasons to use interface. They are given below.
 It is used to achieve abstraction.
 By interface, we can support the functionality of multiple inheritances.
Cloud IT Solution Page 407
 It can be used to achieve loose coupling.
 In other words, Interface fields are public, static and final by default, and methods are
public and abstract.
Java Interface Example: Bank
interface Bank{
float rateOfInterest();
}
class SBI implements Bank{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}}
Multiple inheritances is not supported through class in java but it is possible by interface
As we have explained in the inheritance chapter, multiple inheritances is not supported in case of
class because of ambiguity. But it is supported in case of interface because there is no ambiguity
as implementation is provided by the implementation class. For example:
interface Printable{
void print();
}
interface Showable{
void print();
}
class TestInterface3 implements Printable, Showable{
public void print(){System.out.println("Hello");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.print();
}
}
interface Printable{
int MIN=5;
void print();
}
compiler
interface Printable{
public static final int MIN=5;
public abstract void print();
}
Interface.java Interface.class
Cloud IT Solution Page 408
What is marker or tagged interface?
An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to the
JVM so that JVM may perform some useful operation.
//How Serializable interface is written?
public interface Serializable{
}
Abstract Vs Interface
Abstract class Interface
Abstract class can have abstract and non-
abstract methods.
Interface can have only abstract methods. Since
Java 8, it can have default and static methods
also.
Abstract class doesn't support multiple
inheritance.
Interface supports multiple inheritances.
Abstract class can have final, non-final,
static and non-static variables.
Interface has only static and final variables.
Abstract class can provide the
implementation of interface.
Interface can't provide the implementation of
abstract class.
The abstract keyword is used to declare
abstract class.
The interface keyword is used to declare
interface.
Example:
public abstract class Shape{
public abstract void draw();
}
Example:
public interface Drawable{
void draw();
}
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For
example: capsule, it is wrapped with different medicines.
Code Example
public class Student{
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name=name
}
}
Cloud IT Solution Page 409
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Association
 Association is relation between two separate classes which establishes through their
Objects.
 Association can be one-to-one, one-to-many, many-to-one, many-to-many.
In Object-Oriented programming, an Object communicates to other Object to use
functionality and services provided by that object.
 Composition and Aggregation are the two forms of association
// Java program to illustrate the
// concept of Association
import java.io.*;
// class bank
class Bank
{
private String name;
// bank name
Bank(String name)
{
this.name = name;
}
public String getBankName()
{
return this.name;
}
}
// employee class
class Employee
Association
Aggregation
Composition
Cloud IT Solution Page 410
{
private String name;
// employee name
Employee(String name)
{
this.name = name;
}
public String getEmployeeName()
{
return this.name;
}
}
// Association between both the
// classes in main method
class Association
{
public static void main (String[] args)
{
Bank bank = new Bank("Axis");
Employee emp = new Employee("Neha");
System.out.println(emp.getEmployeeName() +
"is employee of " +
bank.getBankName());
}
}
In above example two separate classes Bank and Employee are associated through their Objects.
Bank can have many employees, so it is a one-to-many relationship.
Aggregation
 It is a special form of Association where
 If a class has an entity reference, it is known as Aggregation. Aggregation represents
HAS-A relationship.
 It represents Has-A relationship.
 It is a unidirectional association i.e. a one way relationship. For example, department
can have students but vice versa is not possible and thus unidirectional in nature.
Bank
Employee 1
Employee 2
Employee 3
Cloud IT Solution Page 411
 In Aggregation, both the entries can survive individually which means ending one
entity will not affect the other entity
 Why use Aggregation
 For Code Reusability
Example
public class Address {
String city,state,country;
public Address(String city, String state, String country) {
this.city = city;
this.state = state;
this.country = country;
}
}
public class Emp {
int id;
String name;
Address address;
public Emp(int id, String name,Address address) {
this.id = id;
this.name = name;
this.address=address;
}
void display(){
System.out.println(id+" "+name);
System.out.println(address.city+" "+address.state+"
"+address.country);
}
public static void main(String[] args) {
Address address1=new Address("gzb","UP","india");
Address address2=new Address("gno","UP","india");
Emp e=new Emp(111,"varun",address1);
Emp e2=new Emp(112,"arun",address2);
e.display();
e2.display();
}
}
Composition
Composition is a restricted form of Aggregation in which two entities are highly dependent on
each other.
 It represents part-of relationship.
 In composition, both the entities are dependent on each other.
 When there is a composition between two entities, the composed object cannot
exist without the other entity.
Cloud IT Solution Page 412
Illustrates a composition relationship between two classes, House and Room
public class House
{
private Room room;
public House()
{
room = new Room();
}
}
Aggregation vs Composition
 Dependency: Aggregation implies a relationship where the child can exist
independently of the parent. For example, Bank and Employee, delete the Bank and the
Employee still exist. Whereas Composition implies a relationship where the child cannot
exist independent of the parent. Example: Human and heart, heart don’t exist separate to
a Human
 Type of Relationship: Aggregation relation is has-a and composition is part-of relation.
 Type of association: Composition is a strong Association whereas Aggregation is a weak
Association.
Access Modifiers
 There are 4 types of java access modifiers:
 private
 default
 protected
 public
Access
Modifier
within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Package
A java package is a group of similar types of classes, interfaces and sub-packages.
Advantage of java package
 Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
 Java package provides access protection.
 Java package removes naming collision.
Cloud IT Solution Page 413
Multithreading
Multithreading is a process of executing multiple threads simultaneously. Its main advantage is-
 Threads share the same address space.
 Thread is lightweight.
 Cost of communication between processes is low.
Thread
A thread is a lightweight sub process. It is a separate path of execution. It is called separate path
of execution because each thread runs in a separate stack frame.
Difference between preemptive scheduling and time slicing
Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead
states or a higher priority task comes into existence. Under time slicing, a task executes for a
predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines
which task should execute next, based on priority and other factors.
What does join () method?
The join() method waits for a thread to die. In other words, it causes the currently running threads
to stop executing until the thread it joins with completes its task.
Difference between wait() and sleep() method
wait() sleep()
The wait() method is defined in Object
class.
The sleep() method is defined in Thread class.
The wait() method releases the lock. The sleep() method doesn't releases the lock.
Is it possible to start a thread twice?
No, there is no possibility to start a thread twice. If we does, it throws an exception.
Cloud IT Solution Page 414
Can we call the run() method instead of start()?
Yes, but it will not work as a thread rather it will work as a normal object so there will not be
context-switching between the threads.
Daemon threads
The daemon threads are basically the low priority threads that provides the background support to
the user threads. It provides services to the user threads.
Can we make the user thread as daemon thread if thread is started?
No, if you do so, it will throw Illegal Thread State Exception
What is shutdown hook?
The shutdown hook is basically a thread i.e. invoked implicitly before JVM shuts down. So we
can use it perform clean up resource.
When should we interrupt a thread?
We should interrupt a thread if we want to break out the sleep or wait state of a thread.
Synchronization
Synchronization is the capabilility of control the access of multiple threads to any shared
resource. It is used:
 To prevent thread interference.
 To prevent consistency problem.
What is the purpose of Synchronized block?
 Synchronized block is used to lock an object for any shared resource.
 Scope of synchronized block is smaller than the method.
Can Java object be locked down for exclusive use by a given thread?
 Yes. You can lock an object by putting it in a synchronized block. The locked object is
inaccessible to any thread other than the one that explicitly claimed it.
 If you make any static method as synchronized, the lock will be on the class not on
object.

Difference between notify() and notifyAll()
The notify () is used to unblock one waiting thread whereas notifyAll() method is used to unblock
all the threads in waiting state.
Deadlock
Deadlock is a situation when two threads are waiting on each other to release a resource. Each
thread waiting for a resource which is held by the other waiting thread.
Cloud IT Solution Page 415
Difference between ArrayList and Vector
ArrayList Vector
ArrayList is not synchronized. Vector is synchronized.
ArrayList is not a legacy class. Vector is a legacy class.
ArrayList increases its size by 50% of the array
size.
Vector increases its size by doubling the array size.
Difference between ArrayList and LinkedList
ArrayList LinkedList
ArrayList uses a dynamic array. LinkedList uses doubly linked list.
ArrayList is not efficient for manipulation because a lot
of shifting is required.
LinkedList is efficient for manipulation.
ArrayList is better to store and fetch data. LinkedList is better to manipulate data.
Difference between Iterator and ListIterator.
Iterator ListIterator
Iterator traverses the elements in forward
direction only.
List Iterator traverses the elements in backward and
forward directions both.
Iterator can be used in List, Set and Queue. List Iterator can be used in List only.
Difference between Iterator and Enumeration
Iterator Enumeration
Iterator can traverse legacy and non-legacy
elements.
Enumeration can traverse only legacy elements.
Iterator is fail-fast. Enumeration is not fail-fast.
Iterator is slower than Enumeration. Enumeration is faster than Iterator.
Difference between List and Set
List can contain duplicate elements whereas Set contains only unique elements.
Difference between HashSet and TreeSet
HashSet maintains no order whereas TreeSet maintains ascending order.
Thread 1 Thread 2
Resource
A
Resource
B
Deadlock
Locks
Locks
Waits
Waits
Cloud IT Solution Page 416
Difference between Set and Map
Set contains values only whereas Map contains key and values both.
Difference between HashSet and HashMap
HashSet contains only values whereas HashMap contains entry (key,value). HashSet can be
iterated but HashMap need to convert into Set to be iterated.
Difference between HashMap and TreeMap
HashMap maintains no order but TreeMap maintains ascending order.
Difference between HashMap and Hashtable
HashMap Hashtable
HashMap is not synchronized. Hashtable is synchronized.
HashMap can contain one null key and multiple null
values.
Hashtable cannot contain any null key or
null value.
Difference between Collection and Collections
Collection is an interface whereas Collections is a class. Collection interface provides normal
functionality of data structure to List, Set and Queue. But, Collections class is to sort and
synchronize collection elements.
Difference between Comparable and Comparator
Comparable Comparator
Comparable provides only one sort of sequence. Comparator provides multiple sort of sequences.
It provides one method named compareTo(). It provides one method named compare().
It is found in java.lang package. it is found in java.util package.
If we implement Comparable interface, actual class
is modified.
Actual class is not modified.
Advantage of Properties file
If you change the value in properties file, you don't need to recompile the java class. So, it makes
the application easy to manage.
HashCode() method
 The hashCode() method returns a hash code value (an integer number).
 The hashCode() method returns the same integer number, if two keys (by calling equals()
method) are same.
 But, it is possible that two hash code numbers can have different or same keys.
Why we override equals() method?
 The equals method is used to check whether two objects are same or not. It needs to be
overridden if we want to check the objects based on property.
 For example, Employee is a class that has 3 data members: id, name and salary. But, we
want to check the equality of employee object on the basis of salary. Then, we need to
override the equals() method.
How to synchronize List, Set and Map elements?
Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
Cloud IT Solution Page 417
public static List synchronizedList(List l){}
public static Set synchronizedSet(Set s){}
public static SortedSet
synchronizedSortedSet(SortedSet s){}
public static Map synchronizedMap(Map m){}
public static SortedMap
synchronizedSortedMap(SortedMap m){}
Advantage of generic collection
If we use generic class, we don't need typecasting. It is type safe and checked at compile time.
Hash-collision in Hashtable and how it is handled in Java
Two different keys with the same hash value are known as hash-collision. Two different entries
will be kept in a single hash bucket to avoid the collision.
Dictionary class
The Dictionary class provides the capability to store key-value pairs.
What is the default size of load factor in hashing based collection?
The default size of load factor is 0.75. The default capacity is computed as initial capacity * load
factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map.
JSP
JSP technology is used to create dynamic web applications. JSP pages are easier to maintain then
a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while
JSP adds Java code inside HTML using JSP tags. Everything a Servlet can do, a JSP page can
also do it.
Advantage of JSP
 Easy to maintain and code.
 High Performance and Scalability.
 JSP is built on Java technology, so it is platform independent.
Lifecycle of JSP
Following are the JSP Lifecycle steps:
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method
Cloud IT Solution Page 418
Components of .Net Framework
1. Common Language Runtime (CLR)
2. Net Framework Class Library (FCL)
3. Common Type System (CTS)
4. Common Language Specification (CLS)
Design Pattern
 Creational design patterns
 Structural design patterns
 Behavioral design patterns
 Architectural design pattern
Creational design patterns
 These design patterns are all about class instantiation. This pattern can be further divided
into class-creation patterns and object-creational patterns. While class-creation patterns
use inheritance effectively in the instantiation process, object-creation patterns use
delegation effectively to get the job done.
 Abstract Factory
Creates an instance of several families of classes
 Builder
Separates object construction from its representation
 Factory Method
Creates an instance of several derived classes
 Object Pool
Avoid expensive acquisition and release of resources by recycling objects that are no
longer in use
 Prototype
A fully initialized instance to be copied or cloned
 Singleton
A class of which only a single instance can exist
Cloud IT Solution Page 419
Structural design patterns
These design patterns are all about Class and Object composition. Structural class-creation
patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose
objects to obtain new functionality.
 Adapter
Match interfaces of different classes
 Bridge
Separates an object’s interface from its implementation
 Composite
A tree structure of simple and composite objects
 Decorator
Add responsibilities to objects dynamically
 Facade
A single class that represents an entire subsystem
 Flyweight
A fine-grained instance used for efficient sharing
 Private Class Data
Restricts access or mutator access
 Proxy
An object representing another object
Behavioral design patterns
These design patterns are all about Class's objects communication. Behavioral patterns are those
patterns that are most specifically concerned with communication between objects-
 Chain of responsibility : A way of passing a request between a chain of objects
 Command: Encapsulate a command request as an object
 Interpreter: A way to include language elements in a program
 Iterator: Sequentially access the elements of a collection
 Mediator: Defines simplified communication between classes
 Memento: Capture and restore an object's internal state
 Null Object: Designed to act as a default value of an object
 Observer: A way of notifying change to a number of classes
 State: Alter an object's behavior when its state changes
 Strategy: Encapsulates an algorithm inside a class
 Template method: Defer the exact steps of an algorithm to a subclass
 Visitor: Defines a new operation to a class without change
Architectural design pattern
MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate
application's concerns.
 Model - Model represents an object or JAVA POJO carrying data. It can also have logic
to update controller if its data changes.
 View - View represents the visualization of the data that model contains.
 Controller - Controller acts on both model and view. It controls the data flow into model
object and updates the view whenever data changes. It keeps view and model separate.
Cloud IT Solution Page 420
Advantages of MVC
 Faster development process
 Ability to provide multiple views
 Support for asynchronous technique
 Modification does not affect the entire model
 MVC model returns the data without formatting
 SEO friendly Development platform
Disadvantages of MVC
 Increased complexity.
 Inefficiency of data access in view
 Difficulty of using MVC with modern user interface.
 Need multiple programmers
 Knowledge on multiple technologies is required.
 Developer has knowledge of client side code and html code.
Constructor Vs Destructor
Types Constructor Destructor
Purpose Constructor is used to initialize the
instance of a class.
Destructor destroys the objects
when they are no longer needed.
When Called Constructor is Called when new instance of
a class is created.
Destructor is called when instance
of a class is deleted or released.
Memory
Management
Constructor allocates the memory. Destructor releases the memory.
Arguments Constructors can have arguments. Destructor cannot have
any arguments.
Overloading Overloading of constructor is possible. Overloading of Destructor is not
possible.
Name Constructor has the same name as class
name.
Destructor also has the same name
as class name but with (~) tiled
operator.
Syntex ClassName(Arguments)
{
//Body of Constructor
}
~ ClassName()
{
}
Cloud IT Solution Page 421
Difference between break and continue
Comparison Break Continue
Task It terminates the execution of
remaining iteration of the loop.
It terminates only the current
iteration of the loop.
Control after
break/continue
break resumes the control of the
program to the end of loop enclosing
that break.
continue resumes the control of
the program to the next iteration
of that loop enclosing continue.
Causes It causes early termination of loop. It causes early execution of the
next iteration.
Continuation break stops the continuation of loop. continue do not stops the
continuation of loop, it only stops
the current iteration.
Other uses break can be used with switch,
label.
continue can not be executed
with switch and labels.
Cloud IT Solution Page 422
1. A default catch block catches
a. all thrown objects b. no thrown objects
c. any thrown object that has not been caught by an earlier catch block
d. all thrown objects that have been caught by an earlier catch block
2. Format flags may be combined using
a. the bitwise OR operator (I) b. the logical OR operator (II)
c. the bitwise AND operator d. the logical AND operator (&&)
3. The use of the break statement in a switch statement is
a. optional b. compulsory
c. not allowed and it gives an error message d. to cheek an error
4. Which of the following are valid characters for a numeric literal constant?
a. a comma b. a dollar sign ($) c. a percent sign (%) d. None of these
5. A function that changes the state of the cout object is called a ____
a. member b. adjuster c. manipulator d. operator
6. A C++ program contains a function with the header int function (double d, char c).
Which of the following function headers could be used within the same program?
a. char function (double d, char c) b. int function (int d, char c)
c. both a and b d. None of these
7. When the compiler cannot differentiate between two overloaded constructors, they are called
a. overloaded b. destructed c. ambiguous d. dubious
8. If you design a class that needs special initialization tasks, you will want to design a/an -
a. housekeeping routine b. initializer c. constructor d. compiler
9. Which type of statement does not occur in computer programs?
a. sequence b. loop c. denial d. selection
10. The newline character is always included between
a. pair of curly braces b. pair of curly braces c. control string d. &
11. To be called object-oriented, a programming language must allow
a. functions that return only a single value b. #include files
c. inheritance b. All of the above
12. A function that returns no values to the program that calls it is.......
a. not allowed in C++ b. Javab. type void
c. type empty d. type barren
13. The keyword used to define a structure is _______
a. stru b. stt c. struct d. structure
14. Header files often have the file extension _____
a .H b. HE c. HEA d..HEAD
15. A function that is called automatically each time an object is destroyed is a
a. constructor b. destructor c. destroyer d. terminator
16. The step-by-step instructions that solve a problem are called ____
a. an algorithm b. a list c. a plan d. a sequential structure
Model Test
Cloud IT Solution Page 423
17. Which of the following statements allows the user to enter data at the keyboard?
a. cin<<currentPay; b. cin>>currentPay;
c. cout<<currentPay; d. cout>>currentPay
18. When you pass a variable _____, C++ passes only the contents of the variable to the
receiving function
a. by reference b. by value c.globally d. locally
19. An Array name is a ____
a. subscript b. formal parameter c. memory address d. prototype
20. To enter a comment in a C++ program, you begin the comment with ___
a. ** b. && c.  d. //
21. Which of the following is (are) invalid string constant(s)?
a. ‘7.50 pm’ b. “I like” c. “7.3e12” d. “1234e12”
22. Overloaded functions are required to
a. have the same return type b. have the same number of parameters
c. perform the same basic functions d. perform the same basic functions
23. You mark the beginning of a function's block of code with the ____
a. / b. * c. { d. }
24. Sending a copy of data to a program module is called _____
a. passing a value b. making a reference c. recursion d. setting a condition
25. A widget is to the blueprint for a widget as an object to
a. a member function b. a class c. an operator d. a data item
26. Which of the following assigns the number 5 to the area variable?
a. area 1=5 b. area = 5 c. area == 5 d. area -->5
27. A base class may also be called a
a. child class b. subclass c. derived class d. parent class
28. When you omit parameters from a function call, values can be provided by
a.formal parameters b. reference parameters c. overloaded parameters d. default parameters
29. The first element in a string is
a. the name of the string b. the first character in the string
c. the length of the string d. the name of the array holding the string
30. Variables declared outside a block are called _____
a. global b. universal c. stellar d. external
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
c a a d c b c c c c c b c a b
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
a b b c d a d c a b b d d b a
Model Test Answer

More Related Content

Similar to 11.Object Oriented Programming.pdf

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
Satya Johnny
 

Similar to 11.Object Oriented Programming.pdf (20)

oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Java ppt Gandhi Ravi (gandhiri@gmail.com)
Java ppt  Gandhi Ravi  (gandhiri@gmail.com)Java ppt  Gandhi Ravi  (gandhiri@gmail.com)
Java ppt Gandhi Ravi (gandhiri@gmail.com)
 
Unit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptxUnit No 3 Inheritance annd Polymorphism.pptx
Unit No 3 Inheritance annd Polymorphism.pptx
 
Polymorphism in java
Polymorphism in java Polymorphism in java
Polymorphism in java
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and InterfacesUNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces
 
Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
Oop
OopOop
Oop
 
oops with java modules i & ii.ppt
oops with java modules i & ii.pptoops with java modules i & ii.ppt
oops with java modules i & ii.ppt
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#Polymorphism in C# Function overloading in C#
Polymorphism in C# Function overloading in C#
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 

More from Export Promotion Bureau

More from Export Promotion Bureau (20)

Advance Technology
Advance TechnologyAdvance Technology
Advance Technology
 
16.psc.pdf
16.psc.pdf16.psc.pdf
16.psc.pdf
 
Advance Technology
Advance TechnologyAdvance Technology
Advance Technology
 
8.Information Security
8.Information Security8.Information Security
8.Information Security
 
14.Linux Command
14.Linux Command14.Linux Command
14.Linux Command
 
12.Digital Logic.pdf
12.Digital Logic.pdf12.Digital Logic.pdf
12.Digital Logic.pdf
 
9.C Programming
9.C Programming9.C Programming
9.C Programming
 
4.Database Management System.pdf
4.Database Management System.pdf4.Database Management System.pdf
4.Database Management System.pdf
 
Lab Question
Lab QuestionLab Question
Lab Question
 
DMZ
DMZDMZ
DMZ
 
loopback address
loopback addressloopback address
loopback address
 
Race Condition
Race Condition Race Condition
Race Condition
 
BCS (WRITTEN) EXAMINATION.pptx
BCS (WRITTEN) EXAMINATION.pptxBCS (WRITTEN) EXAMINATION.pptx
BCS (WRITTEN) EXAMINATION.pptx
 
Nothi_update.pptx
Nothi_update.pptxNothi_update.pptx
Nothi_update.pptx
 
word_power_point_update.pptx
word_power_point_update.pptxword_power_point_update.pptx
word_power_point_update.pptx
 
ICT-Cell.pptx
ICT-Cell.pptxICT-Cell.pptx
ICT-Cell.pptx
 
Incoterms.pptx
Incoterms.pptxIncoterms.pptx
Incoterms.pptx
 
EPB-Flow-Chart.pptx
EPB-Flow-Chart.pptxEPB-Flow-Chart.pptx
EPB-Flow-Chart.pptx
 
Subnetting.pptx
Subnetting.pptxSubnetting.pptx
Subnetting.pptx
 
Software-Development.pptx
Software-Development.pptxSoftware-Development.pptx
Software-Development.pptx
 

Recently uploaded

Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Recently uploaded (20)

SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...Making communications land - Are they received and understood as intended? we...
Making communications land - Are they received and understood as intended? we...
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 

11.Object Oriented Programming.pdf

  • 1. Cloud IT Solution Page 399 Object Oriented Programming System Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts: 1. Object 2. Class 3. Inheritance 4. Polymorphism 5. Abstraction 6. Encapsulation Advantage of OOPs over Procedure-oriented programming language  OOPs makes development and maintenance easier where as in Procedure-oriented programming language it is not easy to manage if code grows as project size grows.  OOPs provide data hiding whereas in Procedure-oriented programming language a global data can be accessed from anywhere.  OOPs provide ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language. Object  Object is a real world entity.  Object is a run time entity.  Object is an entity which has state and behavior.  Object is an instance of a class.  It can be physical or logical (tangible and intangible). The example of intangible object is banking system.  Object is an instance of a class. Class is a template or blueprint from which objects are created. So object is the instance (result) of a class. Object Oriented Programming
  • 2. Cloud IT Solution Page 400 Characteristics  State: represents data (value) of an object.  Behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.  Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. But, it is used internally by the JVM to identify each object uniquely. Code Example class Student{ int id; //field or data member or instance variable String name; public static void main(String args[]){ Student s1=new Student();//creating an object of Student System.out.println(s1.id);//accessing member through reference variable System.out.println(s1.name); } } Class  Collection of objects is called class. It is a logical entity.  A class in Java can contain-  fields  methods  constructors  blocks  nested class and interface Syntax to declare a class class <class_name>{ field; method; } Method  In java, a method is like function i.e. used to expose behavior of an object.  Advantage of Method  Code Reusability  Code Optimization Instance variable  A variable which is created inside the class but outside the method is known as instance variable. Instance variable doesn't get memory at compile time. It gets memory at run time when object (instance) is created. That is why, it is known as instance variable
  • 3. Cloud IT Solution Page 401 Inheritance  When one object acquires all the properties and behaviors of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.  Inheritance represents the IS-A relationship, also known as parent-child relationship. Why use inheritance?  For Method Overriding (so runtime polymorphism can be achieved).  For Code Reusability. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Why multiple inheritances is not supported in java?  To reduce the complexity and simplify the language, multiple inheritances is not supported in java.  Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.  Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now. Employee Salary:float Programmer Bonus:int
  • 4. Cloud IT Solution Page 402 class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{//suppose if it were Public Static void main(String args[]){ C obj=new C(); obj.msg();//Now which msg() method would be invoked? } } Polymorphism  When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.  In java, we use method overloading and method overriding to achieve polymorphism.  Another example can be to speak something e.g. cat speaks meow, dog barks woof etc. Features  Method Overloading.  Method overwriting. Method Overloading  If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.  If we have to perform only one operation, having same name of the methods increases the readability of the program Advantage of method overloading  Method overloading increases the readability of the program. Different ways to overload the method  There are two ways to overload the method in java  By changing number of arguments  By changing the data type
  • 5. Cloud IT Solution Page 403 Method Overloading: changing no. of arguments class Adder{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} } class TestOverloading1{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(11,11,11)); }} Method Overloading: changing data type of arguments class Adder{ static int add(int a, int b){return a+b;} static double add(double a, double b){return a+b;} } class TestOverloading2{ public static void main(String[] args){ System.out.println(Adder.add(11,11)); System.out.println(Adder.add(12.3,12.6)); }} Why Method Overloading is not possible by changing the return type of method only ? In java, method overloading is not possible by changing the return type of the method only because of ambiguity. Let's see how ambiguity may occur: class Adder{ static int add(int a,int b){return a+b;} static double add(int a,int b){return a+b;} } class TestOverloading3{ public static void main(String[] args){ System.out.println(Adder.add(11,11));//ambiguity }} Can we overload java main () method? Yes, by method overloading. You can have any number of main methods in a class by method overloading. But JVM calls main() method which receives string array as arguments only. Let's see the simple example: class TestOverloading4{ public static void main(String[] args){System.out.println("main with String[]");} public static void main(String args){System.out.println("main with String");}
  • 6. Cloud IT Solution Page 404 public static void main(){System.out.println("main without args");} } Output: main with String[] Method Overriding  If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.  In other words, if subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding. Usage of Java Method Overriding  Method overriding is used to provide specific implementation of a method that is already provided by its super class.  Method overriding is used for runtime polymorphism Rules for Java Method Overriding  method must have same name as in the parent class  method must have same parameter as in the parent class.  must be IS-A relationship (inheritance). class Bank{ float getRateOfInterest(){return 0;} } class SBI extends Bank{ float getRateOfInterest(){return 8.4f;} } class ICICI extends Bank{ float getRateOfInterest(){return 7.3f;} } class AXIS extends Bank{ float getRateOfInterest(){return 9.7f;} } Bank getRateOfInerest():float SBI getRateOfInerest():float ICICI getRateOfInerest():float ICICI getRateOfInerest():float extends
  • 7. Cloud IT Solution Page 405 class TestPolymorphism{ public static void main(String args[]){ Bank b; b=new SBI(); System.out.println("SBI Rate of Interest: "+b.getRateOfInterest()); b=new ICICI(); System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest()); b=new AXIS(); System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest()); } Can we override static method?  No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later. Why we cannot override static method?  Because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area. Can we override java main method?  No, because main is a static method. Method Overloading Vs. Method Overriding Method Overloading Method Overriding Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its super class. Method overloading is performed within class. Method overriding occurs in two classes that have IS-A (inheritance) relationship. In case of method overloading, parameter must be different. In case of method overriding, parameter must be same. Method overloading is the example of compile time polymorphism. Method overriding is the example of run time polymorphism. In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. Return type must be same or covariant in method overriding.
  • 8. Cloud IT Solution Page 406 Abstraction  Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing.  In java, we use abstract class and interface to achieve abstraction Code Example class Employee extends Person { private String empCode; public String getEmpCode() { return empCode; } public void setEmpCode(String empCode) { this.empCode = empCode; } } abstract class Person { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public class Main{ public static void main(String args[]){ //Instiating an abstract class gives compile time error //Person p = new Person() ; //This reference variable can acess only those method which are overridden Person person = new Employee(); person.setName("Jatin Kansagara"); System.out.println(person.getName()); } } Interface  An interface in java is a blueprint of a class. It has static constants and abstract methods.  The interface in java is a mechanism to achieve abstraction. There can be only abstract methods in the java interface not method body. It is used to achieve abstraction and multiple inheritance in Java  Java Interface also represents IS-A relationship. Why use Java interface  There are mainly three reasons to use interface. They are given below.  It is used to achieve abstraction.  By interface, we can support the functionality of multiple inheritances.
  • 9. Cloud IT Solution Page 407  It can be used to achieve loose coupling.  In other words, Interface fields are public, static and final by default, and methods are public and abstract. Java Interface Example: Bank interface Bank{ float rateOfInterest(); } class SBI implements Bank{ public float rateOfInterest(){return 9.15f;} } class PNB implements Bank{ public float rateOfInterest(){return 9.7f;} } class TestInterface2{ public static void main(String[] args){ Bank b=new SBI(); System.out.println("ROI: "+b.rateOfInterest()); }} Multiple inheritances is not supported through class in java but it is possible by interface As we have explained in the inheritance chapter, multiple inheritances is not supported in case of class because of ambiguity. But it is supported in case of interface because there is no ambiguity as implementation is provided by the implementation class. For example: interface Printable{ void print(); } interface Showable{ void print(); } class TestInterface3 implements Printable, Showable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ TestInterface3 obj = new TestInterface3(); obj.print(); } } interface Printable{ int MIN=5; void print(); } compiler interface Printable{ public static final int MIN=5; public abstract void print(); } Interface.java Interface.class
  • 10. Cloud IT Solution Page 408 What is marker or tagged interface? An interface that have no member is known as marker or tagged interface. For example: Serializable, Cloneable, Remote etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation. //How Serializable interface is written? public interface Serializable{ } Abstract Vs Interface Abstract class Interface Abstract class can have abstract and non- abstract methods. Interface can have only abstract methods. Since Java 8, it can have default and static methods also. Abstract class doesn't support multiple inheritance. Interface supports multiple inheritances. Abstract class can have final, non-final, static and non-static variables. Interface has only static and final variables. Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. The abstract keyword is used to declare abstract class. The interface keyword is used to declare interface. Example: public abstract class Shape{ public abstract void draw(); } Example: public interface Drawable{ void draw(); } Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully abstraction (100%). Encapsulation Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines. Code Example public class Student{ private String name; public String getName(){ return name; } public void setName(String name){ this.name=name } }
  • 11. Cloud IT Solution Page 409 A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. Association  Association is relation between two separate classes which establishes through their Objects.  Association can be one-to-one, one-to-many, many-to-one, many-to-many. In Object-Oriented programming, an Object communicates to other Object to use functionality and services provided by that object.  Composition and Aggregation are the two forms of association // Java program to illustrate the // concept of Association import java.io.*; // class bank class Bank { private String name; // bank name Bank(String name) { this.name = name; } public String getBankName() { return this.name; } } // employee class class Employee Association Aggregation Composition
  • 12. Cloud IT Solution Page 410 { private String name; // employee name Employee(String name) { this.name = name; } public String getEmployeeName() { return this.name; } } // Association between both the // classes in main method class Association { public static void main (String[] args) { Bank bank = new Bank("Axis"); Employee emp = new Employee("Neha"); System.out.println(emp.getEmployeeName() + "is employee of " + bank.getBankName()); } } In above example two separate classes Bank and Employee are associated through their Objects. Bank can have many employees, so it is a one-to-many relationship. Aggregation  It is a special form of Association where  If a class has an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.  It represents Has-A relationship.  It is a unidirectional association i.e. a one way relationship. For example, department can have students but vice versa is not possible and thus unidirectional in nature. Bank Employee 1 Employee 2 Employee 3
  • 13. Cloud IT Solution Page 411  In Aggregation, both the entries can survive individually which means ending one entity will not affect the other entity  Why use Aggregation  For Code Reusability Example public class Address { String city,state,country; public Address(String city, String state, String country) { this.city = city; this.state = state; this.country = country; } } public class Emp { int id; String name; Address address; public Emp(int id, String name,Address address) { this.id = id; this.name = name; this.address=address; } void display(){ System.out.println(id+" "+name); System.out.println(address.city+" "+address.state+" "+address.country); } public static void main(String[] args) { Address address1=new Address("gzb","UP","india"); Address address2=new Address("gno","UP","india"); Emp e=new Emp(111,"varun",address1); Emp e2=new Emp(112,"arun",address2); e.display(); e2.display(); } } Composition Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.  It represents part-of relationship.  In composition, both the entities are dependent on each other.  When there is a composition between two entities, the composed object cannot exist without the other entity.
  • 14. Cloud IT Solution Page 412 Illustrates a composition relationship between two classes, House and Room public class House { private Room room; public House() { room = new Room(); } } Aggregation vs Composition  Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. Whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human  Type of Relationship: Aggregation relation is has-a and composition is part-of relation.  Type of association: Composition is a strong Association whereas Aggregation is a weak Association. Access Modifiers  There are 4 types of java access modifiers:  private  default  protected  public Access Modifier within class within package outside package by subclass only outside package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y Package A java package is a group of similar types of classes, interfaces and sub-packages. Advantage of java package  Java package is used to categorize the classes and interfaces so that they can be easily maintained.  Java package provides access protection.  Java package removes naming collision.
  • 15. Cloud IT Solution Page 413 Multithreading Multithreading is a process of executing multiple threads simultaneously. Its main advantage is-  Threads share the same address space.  Thread is lightweight.  Cost of communication between processes is low. Thread A thread is a lightweight sub process. It is a separate path of execution. It is called separate path of execution because each thread runs in a separate stack frame. Difference between preemptive scheduling and time slicing Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. What does join () method? The join() method waits for a thread to die. In other words, it causes the currently running threads to stop executing until the thread it joins with completes its task. Difference between wait() and sleep() method wait() sleep() The wait() method is defined in Object class. The sleep() method is defined in Thread class. The wait() method releases the lock. The sleep() method doesn't releases the lock. Is it possible to start a thread twice? No, there is no possibility to start a thread twice. If we does, it throws an exception.
  • 16. Cloud IT Solution Page 414 Can we call the run() method instead of start()? Yes, but it will not work as a thread rather it will work as a normal object so there will not be context-switching between the threads. Daemon threads The daemon threads are basically the low priority threads that provides the background support to the user threads. It provides services to the user threads. Can we make the user thread as daemon thread if thread is started? No, if you do so, it will throw Illegal Thread State Exception What is shutdown hook? The shutdown hook is basically a thread i.e. invoked implicitly before JVM shuts down. So we can use it perform clean up resource. When should we interrupt a thread? We should interrupt a thread if we want to break out the sleep or wait state of a thread. Synchronization Synchronization is the capabilility of control the access of multiple threads to any shared resource. It is used:  To prevent thread interference.  To prevent consistency problem. What is the purpose of Synchronized block?  Synchronized block is used to lock an object for any shared resource.  Scope of synchronized block is smaller than the method. Can Java object be locked down for exclusive use by a given thread?  Yes. You can lock an object by putting it in a synchronized block. The locked object is inaccessible to any thread other than the one that explicitly claimed it.  If you make any static method as synchronized, the lock will be on the class not on object.  Difference between notify() and notifyAll() The notify () is used to unblock one waiting thread whereas notifyAll() method is used to unblock all the threads in waiting state. Deadlock Deadlock is a situation when two threads are waiting on each other to release a resource. Each thread waiting for a resource which is held by the other waiting thread.
  • 17. Cloud IT Solution Page 415 Difference between ArrayList and Vector ArrayList Vector ArrayList is not synchronized. Vector is synchronized. ArrayList is not a legacy class. Vector is a legacy class. ArrayList increases its size by 50% of the array size. Vector increases its size by doubling the array size. Difference between ArrayList and LinkedList ArrayList LinkedList ArrayList uses a dynamic array. LinkedList uses doubly linked list. ArrayList is not efficient for manipulation because a lot of shifting is required. LinkedList is efficient for manipulation. ArrayList is better to store and fetch data. LinkedList is better to manipulate data. Difference between Iterator and ListIterator. Iterator ListIterator Iterator traverses the elements in forward direction only. List Iterator traverses the elements in backward and forward directions both. Iterator can be used in List, Set and Queue. List Iterator can be used in List only. Difference between Iterator and Enumeration Iterator Enumeration Iterator can traverse legacy and non-legacy elements. Enumeration can traverse only legacy elements. Iterator is fail-fast. Enumeration is not fail-fast. Iterator is slower than Enumeration. Enumeration is faster than Iterator. Difference between List and Set List can contain duplicate elements whereas Set contains only unique elements. Difference between HashSet and TreeSet HashSet maintains no order whereas TreeSet maintains ascending order. Thread 1 Thread 2 Resource A Resource B Deadlock Locks Locks Waits Waits
  • 18. Cloud IT Solution Page 416 Difference between Set and Map Set contains values only whereas Map contains key and values both. Difference between HashSet and HashMap HashSet contains only values whereas HashMap contains entry (key,value). HashSet can be iterated but HashMap need to convert into Set to be iterated. Difference between HashMap and TreeMap HashMap maintains no order but TreeMap maintains ascending order. Difference between HashMap and Hashtable HashMap Hashtable HashMap is not synchronized. Hashtable is synchronized. HashMap can contain one null key and multiple null values. Hashtable cannot contain any null key or null value. Difference between Collection and Collections Collection is an interface whereas Collections is a class. Collection interface provides normal functionality of data structure to List, Set and Queue. But, Collections class is to sort and synchronize collection elements. Difference between Comparable and Comparator Comparable Comparator Comparable provides only one sort of sequence. Comparator provides multiple sort of sequences. It provides one method named compareTo(). It provides one method named compare(). It is found in java.lang package. it is found in java.util package. If we implement Comparable interface, actual class is modified. Actual class is not modified. Advantage of Properties file If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage. HashCode() method  The hashCode() method returns a hash code value (an integer number).  The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same.  But, it is possible that two hash code numbers can have different or same keys. Why we override equals() method?  The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property.  For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method. How to synchronize List, Set and Map elements? Yes, Collections class provides methods to make List, Set or Map elements as synchronized:
  • 19. Cloud IT Solution Page 417 public static List synchronizedList(List l){} public static Set synchronizedSet(Set s){} public static SortedSet synchronizedSortedSet(SortedSet s){} public static Map synchronizedMap(Map m){} public static SortedMap synchronizedSortedMap(SortedMap m){} Advantage of generic collection If we use generic class, we don't need typecasting. It is type safe and checked at compile time. Hash-collision in Hashtable and how it is handled in Java Two different keys with the same hash value are known as hash-collision. Two different entries will be kept in a single hash bucket to avoid the collision. Dictionary class The Dictionary class provides the capability to store key-value pairs. What is the default size of load factor in hashing based collection? The default size of load factor is 0.75. The default capacity is computed as initial capacity * load factor. For example, 16 * 0.75 = 12. So, 12 is the default capacity of Map. JSP JSP technology is used to create dynamic web applications. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything a Servlet can do, a JSP page can also do it. Advantage of JSP  Easy to maintain and code.  High Performance and Scalability.  JSP is built on Java technology, so it is platform independent. Lifecycle of JSP Following are the JSP Lifecycle steps: 1. Translation of JSP to Servlet code. 2. Compilation of Servlet to bytecode. 3. Loading Servlet class. 4. Creating servlet instance. 5. Initialization by calling jspInit() method 6. Request Processing by calling _jspService() method 7. Destroying by calling jspDestroy() method
  • 20. Cloud IT Solution Page 418 Components of .Net Framework 1. Common Language Runtime (CLR) 2. Net Framework Class Library (FCL) 3. Common Type System (CTS) 4. Common Language Specification (CLS) Design Pattern  Creational design patterns  Structural design patterns  Behavioral design patterns  Architectural design pattern Creational design patterns  These design patterns are all about class instantiation. This pattern can be further divided into class-creation patterns and object-creational patterns. While class-creation patterns use inheritance effectively in the instantiation process, object-creation patterns use delegation effectively to get the job done.  Abstract Factory Creates an instance of several families of classes  Builder Separates object construction from its representation  Factory Method Creates an instance of several derived classes  Object Pool Avoid expensive acquisition and release of resources by recycling objects that are no longer in use  Prototype A fully initialized instance to be copied or cloned  Singleton A class of which only a single instance can exist
  • 21. Cloud IT Solution Page 419 Structural design patterns These design patterns are all about Class and Object composition. Structural class-creation patterns use inheritance to compose interfaces. Structural object-patterns define ways to compose objects to obtain new functionality.  Adapter Match interfaces of different classes  Bridge Separates an object’s interface from its implementation  Composite A tree structure of simple and composite objects  Decorator Add responsibilities to objects dynamically  Facade A single class that represents an entire subsystem  Flyweight A fine-grained instance used for efficient sharing  Private Class Data Restricts access or mutator access  Proxy An object representing another object Behavioral design patterns These design patterns are all about Class's objects communication. Behavioral patterns are those patterns that are most specifically concerned with communication between objects-  Chain of responsibility : A way of passing a request between a chain of objects  Command: Encapsulate a command request as an object  Interpreter: A way to include language elements in a program  Iterator: Sequentially access the elements of a collection  Mediator: Defines simplified communication between classes  Memento: Capture and restore an object's internal state  Null Object: Designed to act as a default value of an object  Observer: A way of notifying change to a number of classes  State: Alter an object's behavior when its state changes  Strategy: Encapsulates an algorithm inside a class  Template method: Defer the exact steps of an algorithm to a subclass  Visitor: Defines a new operation to a class without change Architectural design pattern MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.  Model - Model represents an object or JAVA POJO carrying data. It can also have logic to update controller if its data changes.  View - View represents the visualization of the data that model contains.  Controller - Controller acts on both model and view. It controls the data flow into model object and updates the view whenever data changes. It keeps view and model separate.
  • 22. Cloud IT Solution Page 420 Advantages of MVC  Faster development process  Ability to provide multiple views  Support for asynchronous technique  Modification does not affect the entire model  MVC model returns the data without formatting  SEO friendly Development platform Disadvantages of MVC  Increased complexity.  Inefficiency of data access in view  Difficulty of using MVC with modern user interface.  Need multiple programmers  Knowledge on multiple technologies is required.  Developer has knowledge of client side code and html code. Constructor Vs Destructor Types Constructor Destructor Purpose Constructor is used to initialize the instance of a class. Destructor destroys the objects when they are no longer needed. When Called Constructor is Called when new instance of a class is created. Destructor is called when instance of a class is deleted or released. Memory Management Constructor allocates the memory. Destructor releases the memory. Arguments Constructors can have arguments. Destructor cannot have any arguments. Overloading Overloading of constructor is possible. Overloading of Destructor is not possible. Name Constructor has the same name as class name. Destructor also has the same name as class name but with (~) tiled operator. Syntex ClassName(Arguments) { //Body of Constructor } ~ ClassName() { }
  • 23. Cloud IT Solution Page 421 Difference between break and continue Comparison Break Continue Task It terminates the execution of remaining iteration of the loop. It terminates only the current iteration of the loop. Control after break/continue break resumes the control of the program to the end of loop enclosing that break. continue resumes the control of the program to the next iteration of that loop enclosing continue. Causes It causes early termination of loop. It causes early execution of the next iteration. Continuation break stops the continuation of loop. continue do not stops the continuation of loop, it only stops the current iteration. Other uses break can be used with switch, label. continue can not be executed with switch and labels.
  • 24. Cloud IT Solution Page 422 1. A default catch block catches a. all thrown objects b. no thrown objects c. any thrown object that has not been caught by an earlier catch block d. all thrown objects that have been caught by an earlier catch block 2. Format flags may be combined using a. the bitwise OR operator (I) b. the logical OR operator (II) c. the bitwise AND operator d. the logical AND operator (&&) 3. The use of the break statement in a switch statement is a. optional b. compulsory c. not allowed and it gives an error message d. to cheek an error 4. Which of the following are valid characters for a numeric literal constant? a. a comma b. a dollar sign ($) c. a percent sign (%) d. None of these 5. A function that changes the state of the cout object is called a ____ a. member b. adjuster c. manipulator d. operator 6. A C++ program contains a function with the header int function (double d, char c). Which of the following function headers could be used within the same program? a. char function (double d, char c) b. int function (int d, char c) c. both a and b d. None of these 7. When the compiler cannot differentiate between two overloaded constructors, they are called a. overloaded b. destructed c. ambiguous d. dubious 8. If you design a class that needs special initialization tasks, you will want to design a/an - a. housekeeping routine b. initializer c. constructor d. compiler 9. Which type of statement does not occur in computer programs? a. sequence b. loop c. denial d. selection 10. The newline character is always included between a. pair of curly braces b. pair of curly braces c. control string d. & 11. To be called object-oriented, a programming language must allow a. functions that return only a single value b. #include files c. inheritance b. All of the above 12. A function that returns no values to the program that calls it is....... a. not allowed in C++ b. Javab. type void c. type empty d. type barren 13. The keyword used to define a structure is _______ a. stru b. stt c. struct d. structure 14. Header files often have the file extension _____ a .H b. HE c. HEA d..HEAD 15. A function that is called automatically each time an object is destroyed is a a. constructor b. destructor c. destroyer d. terminator 16. The step-by-step instructions that solve a problem are called ____ a. an algorithm b. a list c. a plan d. a sequential structure Model Test
  • 25. Cloud IT Solution Page 423 17. Which of the following statements allows the user to enter data at the keyboard? a. cin<<currentPay; b. cin>>currentPay; c. cout<<currentPay; d. cout>>currentPay 18. When you pass a variable _____, C++ passes only the contents of the variable to the receiving function a. by reference b. by value c.globally d. locally 19. An Array name is a ____ a. subscript b. formal parameter c. memory address d. prototype 20. To enter a comment in a C++ program, you begin the comment with ___ a. ** b. && c. d. // 21. Which of the following is (are) invalid string constant(s)? a. ‘7.50 pm’ b. “I like” c. “7.3e12” d. “1234e12” 22. Overloaded functions are required to a. have the same return type b. have the same number of parameters c. perform the same basic functions d. perform the same basic functions 23. You mark the beginning of a function's block of code with the ____ a. / b. * c. { d. } 24. Sending a copy of data to a program module is called _____ a. passing a value b. making a reference c. recursion d. setting a condition 25. A widget is to the blueprint for a widget as an object to a. a member function b. a class c. an operator d. a data item 26. Which of the following assigns the number 5 to the area variable? a. area 1=5 b. area = 5 c. area == 5 d. area -->5 27. A base class may also be called a a. child class b. subclass c. derived class d. parent class 28. When you omit parameters from a function call, values can be provided by a.formal parameters b. reference parameters c. overloaded parameters d. default parameters 29. The first element in a string is a. the name of the string b. the first character in the string c. the length of the string d. the name of the array holding the string 30. Variables declared outside a block are called _____ a. global b. universal c. stellar d. external 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 c a a d c b c c c c c b c a b 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 a b b c d a d c a b b d d b a Model Test Answer