Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 79

Difference Between OOP and POP

oriented Programming(POP) and Object-oriented programming(OOP) both are the


programming approaches, which uses high-level language for programming. A program can be
written in both the languages, but if the task is highly complex, OOP operates well as compared to
POP. In POP, the ‘data security’ is at risk as data freely moves in the program, as well as, ‘code
reusability’ is not achieved which makes the programming lengthy, and hard to understand.Large
programs lead to more bugs, and it increases the time of debugging. All these flaws lead to a new
approach, namely “object-oriented programming”. In object-oriented programming’s primary
concern is given on ‘data security’; it binds the data closely to the functions which operate on it.
It also resolves the problem of ‘code reusability’, as if a class is created, its multiple
instances(objects) can be created which reuses the members and member functions defined by a
class.

There are some other differences which can be explained with the help of a comparison chart.

Content: OOP Vs POP


1. Comparison Chart
2. Definition
3. Key Differences
4. Advantages
5. Disadvantages
6. Conclusion

Comparison Chart

BASIS FOR POP OOP

COMPARISON

Basic Procedure/Structure oriented Object oriented.

Approach Top-down. Bottom-up.


Basis Main focus is on "how to get Main focus is on 'data security'. Hence, only

the task done" i.e. on the objects are permitted to access the entities of

procedure or structure of a a class.

program .

Division Large program is divided Entire program is divided into objects.

into units called functions.

Entity accessing mode No access specifier Access specifier are "public", "private",

observed. "protected".

Overloading/Polymorphism Neither it overload functions It overloads functions, constructors, and

nor operators. operators.

Inheritance Their is no provision of Inheritance achieved in three modes public

inheritance. private and protected.

Data hiding & security There is no proper way of Data is hidden in three modes public,

hiding the data, so data is private, and protected. hence data security

insecure increases.

Data sharing Global data is shared among Data is shared among the objects through the

the functions in the program. member functions.

Friend functions/classes No concept of friend Classes or function can become a friend of

function. another class with the keyword "friend".

Note: "friend" keyword is used only in c++


Virtual classes/ function No concept of virtual classes Concept of virtual function appear during

. inheritance.

Example C, VB, FORTRAN, Pascal C++, JAVA, VB.NET, C#.NET.

Definition of Object-oriented programming(OOP)

OOP’s chief concern is to hide the data from non-member functions of a class, which it treats like
“critical information”. Data is closely tied to the member functions of a class, which operates on
it. It doesn’t allow any non-member function to modify the data inside it. Objects interact with
each other through member functions to access their data.

OOP is developed on the basic concept of “object”, “classes”, “data encapsulation or abstraction”,”
inheritance”, and “Polymorphism/overloading”. In OOP, programs can be divided into modules
by partitioning data and functions, which further can be used as templates for creating new copies
of modules, if required. Therefore, it is an approach that facilitates in modularizing programs by
constructing a partitioned memory area for data and functions.Object-Oriented Concepts

 Objects: It is considered as a variable of type class and an instance of a class.


 Class: It is a set of objects of similar type. A complete set of data and code of an object creates an
user-defined data type by using a class.
 Data abstraction and encapsulation: Abstraction is nothing but a method of hiding background
details and representing essential features. The encapsulation is a method of packing the data and
functions into a single unit.
 Inheritance: Inheritance is a technique of acquiring features of objects from one class to the other
class objects. In other words, it helps in deriving a new class from the existing one.
 Polymorphism: Polymorphism provides a method of creating multiple forms of a function by using
a single function name.
 Dynamic binding: It specifies that the code associated with a particular procedure is not known until
the moment of the call at run time.
 Message passing: This OOP concept enables interaction between different classes by transmitting
and receiving information.

Definition of Procedure oriented programming(POP)

POP is a conventional way of programming. Procedural programming is where the primary focus
is on getting the task done in sequential order. Flowchart organizes the flow of control of the
program. If the program is extensive, it is structured in some small units called functions, which
shares global data. Here, the concern of data security arises, as there is an unintentional change in
the program by functions.

POP characteristics
 While designing a program, POP follows a top-down programming approach.
 Majority of the functions allows global data to be shared.
 It also divides larger programs into smaller parts called as functions.
 It allows a free data movement around the system from functions to functions.
 Data is transformed by the functions from one form to another.
 It gives importance to the concept of the functions.

1. Key Differences Between OOP and POP


2. POP is procedure-oriented programming while, OOP is object-oriented programming.
3. The main focus of POP is on “how to get the task done” it follows the flow chart to get the task
done. OOP’s main focus is on data security as only the objects of a class are allowed to access the
attributes or function of a class.
4. The functions are small units of the large programs or a sub-program that execute to get the main
task done. In contrast, OOP attributes and functions of the class are divided among the objects.
5. In POP, there is no specific accessing mode to access attributes or functions in the program.
Conversely, in OOP there are three accessing modes “public”, “private”, “protected”, that are
used as an accessing method to access attributes or functions.
6. POP does not support the concept of Overloading/polymorphism. On the contrary, OOP supports
Overloading/Polymorphism, which means using the same function name for performing different
functions. We can overload functions, constructor, and operators in OOP.
7. There is no concept of inheritance in POP whereas, OOP supports inheritance which allows using
the attribute and functions of other class by inheriting it.
8. POP is less secure as compared to OOP because in OOP the access specifier limits the access to
attributes or functions which increase the security.
9. In POP if some data is to be shared among all the functions in the program, it is declared globally
outside all functions. While in OOP the data member of the class can be accessed through the
member functions of the class.
10. In POP there is no concept of the friend function. As against, in OOP there is a concept of friend
function which is not the member of the class, but because it is friend member it can access the
data member and member functions of the class.
11. There is no concept of virtual classes in POP whereas in OOP, the virtual functions support
polymorphism.

Advantages

POP (Procedure Oriented Programming)

 Provides an ability to reuse the same code at various places.


 Facilitates in tracking the program flow.
 Capable of constructing modules.

OOP (Object Oriented Programming)

 Objects help in task partitioning in the project.


 Secure programs can be built using data hiding.
 It can potentially map the objects.
 Enables the categorization of the objects into various classes.
 Object-oriented systems can be upgraded effortlessly.
 Redundant codes can be eliminated using inheritance.
 Codes can be extended using reusability.
 Greater modularity can be achieved.
 Data abstraction increases reliability.
 Flexible due to the dynamic binding concept.
 Decouples the essential specification from its implementation by using information hiding.

Disadvantages

POP (Procedure Oriented Programming

 Global data are vulnerable.


 Data can move freely within a program
 It is tough to verify the data position.
 Functions are action-oriented.
 Functions are not capable of relating to the elements of the problem.
 Real-world problems cannot be modelled.
 Parts of code are interdependent.
 One application code cannot be used in other application.
 Data is transferred by using the functions.

OOP (Object Oriented Programming)

 It requires more resources.


 Dynamic behaviour of objects requires RAM storage.
 Detection and debugging is harder in complex applications when the message passing is performed.
 Inheritance makes their classes tightly coupled, which affects the reusability of objects.

Conclusion

The flaws of POP arises the need for OOP. OOP corrects the flaws of POP by introducing the
concept of “object” and “classes”. It enhances the data security and automatic initialization &
clear-up of objects. OOP makes it possible to create multiple instances of the object without any
interference.
Section- B
Object-oriented Methodology:
The object modeling techniques is an methodology of object oriented analysis,
design and implementation that focuses on creating a model of objects from the real
world and then to use this model to develop object–oriented software. object
modeling technique, OMT was developed by James Rambaugh. Now-a-days,
OMT is one of the most popular object oriented development techniques. It is
primarily used by system and software developers to support full life cycle
development while targeting object oriented implementations. The OMT methodology
covers the full software development life cycle.
Benefits of Object Oriented Methodologies

1. It represents the problem domain, because it is easier to produce and understand


designs.

2. It allows changes more easily.

3. It provides nice structures for thinking, abstracting and leads to modular design.
4. Simplicity:
 The software object's model complexity is reduced and the program structure is very clear.
5. Reusability:
 It is a desired goal of all development process.
 It contains both data and functions which act on data.
 It makes easy to reuse the code in a new system.
 Messages provide a predefined interface to an object's data and functionality.
6. Increased Quality:
 This feature increases in quality is largely a by-product of this program reuse.
7. Maintainable:
 The OOP method makes code more maintainable.
 The objects can be maintained separately, making locating and fixing problems easier.
8. Scalable:
 The object oriented applications are more scalable than structured approach.
 It makes easy to replace the old and aging code with faster algorithms and newer technology.
9. Modularity:
 The OOD systems are easier to modify.
 It can be altered in fundamental ways without ever breaking up since changes are neatly
encapsulated.
10. Modifiability:
 It is easy to make minor changes in the data representation or the procedures in an object
oriented program.
11. Client/Server Architecture:
 It involves the transmission of messages back and forth over a network.

Object-Oriented analysis: In the system analysis or object-oriented analysis


phase of software development, the system requirements are determined, the classes are
identified and the relationships among classes are identified.

1-Object Modelling
Object modelling develops the static structure of the software system in terms of objects.
It identifies the objects, the classes into which the objects can be grouped into and the
relationships between the objects. It also identifies the main attributes and operations that
characterize each class.
The process of object modelling can be visualized in the following steps −

 Identify objects and group into classes


 Identify the relationships among classes
 Create user object model diagram
 Define user object attributes
 Define the operations that should be performed on the classes
 Review glossary

2-Dynamic Modelling
After the static behavior of the system is analyzed, its behavior with respect to time and
external changes needs to be examined. This is the purpose of dynamic modelling.
Dynamic Modelling can be defined as “a way of describing how an individual object
responds to events, either internal events triggered by other objects, or external events
triggered by the outside world”.
The process of dynamic modelling can be visualized in the following steps −

 Identify states of each object


 Identify events and analyze the applicability of actions
 Construct dynamic model diagram, comprising of state transition diagrams
 Express each state in terms of object attributes
 Validate the state–transition diagrams drawn

3-Functional Modelling
Functional Modelling is the final component of object-oriented analysis. The functional
model shows the processes that are performed within an object and how the data changes
as it moves between methods. It specifies the meaning of the operations of object
modelling and the actions of dynamic modelling. The functional model corresponds to the
data flow diagram of traditional structured analysis.
The process of functional modelling can be visualized in the following steps −

 Identify all the inputs and outputs


 Construct data flow diagrams showing functional dependencies
 State the purpose of each function
 Identify constraints
 Specify optimization criteria
Advantages/Disadvantages of Object Oriented Analysis

Advantages Disadvantages

Focuses on data rather than the procedures as in Functionality is restricted within objects. This may
Structured Analysis. pose a problem for systems which are intrinsically
procedural or computational in nature.

The principles of encapsulation and data hiding It cannot identify which objects would generate an
help the developer to develop systems that cannot optimal system design.
be tampered by other parts of the system.

The principles of encapsulation and data hiding The object-oriented models do not easily show the
help the developer to develop systems that cannot communications between the objects in the system.
be tampered by other parts of the system.

It allows effective management of software All the interfaces between the objects cannot be
complexity by the virtue of modularity. represented in a single diagram.

It can be upgraded from small to large systems at a


greater ease than in systems following structured
analysis.

Problem Statement: The first step in the research process is to choose a problem
to investigate. The researcher begins with a general topic and then narrows it to a specific
problem statement, which is a detailed description of the problem and its importance.
A problem statement describes the research problem and identifies potential causes or
solutions. A problem statement also conveys the reason the problem is important and who
is affected by the problem.

Types:There are two general types of problem statements: quantitative and qualitative.
The problem statement in a quantitative research study names the variables and population
to be studied, and asks a question about the relationship between the variables. A
qualitative study, on the other hand, also begins with a problem statement, but it is stated
much more broadly than in a quantitative study. In other words, it states the general purpose
of the study, but the focus may change as the study progresses.
Characteristics

According to "Introduction to Research in Education," a good research problem has five


basic characteristics. The problem must be significant enough to contribute to the existing
body of research; the problem must be one that will lead to more research; it must be
possible to investigate the problem through the collection of data; the problem must be
interesting to the researcher and suit his skills, time and resources and the problem is ethical
and will not harm others.

example of Analysis Process using Object:pass


Overview of System Design: Systems development is systematic process
which includes phases such as planning, analysis, design, deployment, and maintenance.
Here, in this tutorial, we will primarily focus on −

 Systems analysis
 Systems design

Systems Analysis
It is a process of collecting and interpreting facts, identifying the problems, and decomposition
of a system into its components.
System analysis is conducted for the purpose of studying a system or its parts in order to identify
its objectives. It is a problem solving technique that improves the system and ensures that all the
components of the system work efficiently to accomplish their purpose.
Analysis specifies what the system should do.

Systems Design
It is a process of planning a new business system or replacing an existing system by defining its
components or modules to satisfy the specific requirements. Before planning, you need to
understand the old system thoroughly and determine how computers can best be used in order to
operate efficiently.
System Design focuses on how to accomplish the objective of the system.
System Analysis and Design (SAD) mainly focuses on −

 Systems
 Processes
 Technology
What is a System?
The word System is derived from Greek word System, which means an organized relationship
between any set of components to achieve some common cause or objective.
Constraints of a System
A system must have three basic constraints −
 A system must have some structure and behavior which is designed to achieve a
predefined objective.
 Interconnectivity and interdependence must exist among the system
components.
 The objectives of the organization have a higher priority than the objectives of
its subsystems.
For example, traffic management system, payroll system, automatic library system,
human resources information system.

Properties of a System
A system has the following properties −

Organization
Organization implies structure and order. It is the arrangement of components that
helps to achieve predetermined objectives.

Interaction
It is defined by the manner in which the components operate with each other.
For example, in an organization, purchasing department must interact with
production department and payroll with personnel department.

Interdependence
Interdependence means how the components of a system depend on one another.
For proper functioning, the components are coordinated and linked together
according to a specified plan. The output of one subsystem is the required by other
subsystem as input.
Integration
Integration is concerned with how a system components are connected together. It
means that the parts of the system work together within the system even if each part
performs a unique function.

Central Objective
The objective of system must be central. It may be real or stated. It is not uncommon
for an organization to state an objective and operate to achieve another.
The users must know the main objective of a computer application early in the
analysis for a successful design and conversion.

Elements of a System
The following diagram shows the elements of a system −

Outputs and Inputs


 The main aim of a system is to produce an output which is useful for its user.
 Inputs are the information that enters into the system for processing.
 Output is the outcome of processing.

Processor(s)
 The processor is the element of a system that involves the actual transformation of input into
output.
 It is the operational component of a system. Processors may modify the input either totally or
partially, depending on the output specification.
 As the output specifications change, so does the processing. In some cases, input is also modified
to enable the processor for handling the transformation.

Control
 The control element guides the system.
 It is the decision–making subsystem that controls the pattern of activities governing input,
processing, and output.
 The behavior of a computer System is controlled by the Operating System and software. In order
to keep system in balance, what and how much input is needed is determined by Output
Specifications.

Feedback
 Feedback provides the control in a dynamic system.
 Positive feedback is routine in nature that encourages the performance of the system.
 Negative feedback is informational in nature that provides the controller with information for
action.

Environment
 The environment is the “supersystem” within which an organization operates.
 It is the source of external elements that strike on the system.
 It determines how a system must function. For example, vendors and competitors of organization’s
environment, may provide constraints that affect the actual performance of the business.

Boundaries and Interface


 A system should be defined by its boundaries. Boundaries are the limits that identify its
components, processes, and interrelationship when it interfaces with another system.
 Each system has boundaries that determine its sphere of influence and control.
 The knowledge of the boundaries of a given system is crucial in determining the nature of its
interface with other systems for successful design.

Types of Systems
The systems can be divided into the following types −
Physical or Abstract Systems
 Physical systems are tangible entities. We can touch and feel them.
 Physical System may be static or dynamic in nature. For example, desks and chairs are the physical
parts of computer center which are static. A programmed computer is a dynamic system in which
programs, data, and applications can change according to the user's needs.
 Abstract systems are non-physical entities or conceptual that may be formulas, representation or
model of a real system.

Open or Closed Systems


 An open system must interact with its environment. It receives inputs from and delivers outputs to
the outside of the system. For example, an information system which must adapt to the changing
environmental conditions.
 A closed system does not interact with its environment. It is isolated from environmental
influences. A completely closed system is rare in reality.

Adaptive and Non Adaptive System


 Adaptive System responds to the change in the environment in a way to improve their performance
and to survive. For example, human beings, animals.
 Non Adaptive System is the system which does not respond to the environment. For example,
machines.

Permanent or Temporary System


 Permanent System persists for long time. For example, business policies.
 Temporary System is made for specified time and after that they are demolished. For example, A
DJ system is set up for a program and it is dissembled after the program.

Natural and Manufactured System


 Natural systems are created by the nature. For example, Solar system, seasonal system.
 Manufactured System is the man-made system. For example, Rockets, dams, trains.

Deterministic or Probabilistic System


 Deterministic system operates in a predictable manner and the interaction between system
components is known with certainty. For example, two molecules of hydrogen and one molecule
of oxygen makes water.
 Probabilistic System shows uncertain behavior. The exact output is not known. For example,
Weather forecasting, mail delivery.
Social, Human-Machine, Machine System
 Social System is made up of people. For example, social clubs, societies.
 In Human-Machine System, both human and machines are involved to perform a particular task.
For example, Computer programming.
 Machine System is where human interference is neglected. All the tasks are performed by the
machine. For example, an autonomous robot.

Man–Made Information Systems


 It is an interconnected set of information resources to manage data for particular organization,
under Direct Management Control (DMC).
 This system includes hardware, software, communication, data, and application for producing
information according to the need of an organization.
Man-made information systems are divided into three types −
 Formal Information System − It is based on the flow of information in the form of memos,
instructions, etc., from top level to lower levels of management.
 Informal Information System − This is employee based system which solves the day to day work
related problems.
 Computer Based System − This system is directly dependent on the computer for managing
business applications. For example, automatic library system, railway reservation system, banking
system, etc.

Systems Models

Schematic Models
 A schematic model is a 2-D chart that shows system elements and their linkages.
 Different arrows are used to show information flow, material flow, and information feedback.

Flow System Models


 A flow system model shows the orderly flow of the material, energy, and information that hold the
system together.
 Program Evaluation and Review Technique (PERT), for example, is used to abstract a real world
system in model form.

Static System Models


 They represent one pair of relationships such as activity–time or cost–quantity.
 The Gantt chart, for example, gives a static picture of an activity-time relationship.
Dynamic System Models
 Business organizations are dynamic systems. A dynamic model approximates the type of
organization or application that analysts deal with.
 It shows an ongoing, constantly changing status of the system. It consists of −
o Inputs that enter the system
o The processor through which transformation takes place
o The program(s) required for processing
o The output(s) that result from processing.

Categories of Information
There are three categories of information related to managerial levels and the
decision managers make.

Strategic Information
 This information is required by topmost management for long range planning policies for next few
years. For example, trends in revenues, financial investment, and human resources, and population
growth.
 This type of information is achieved with the aid of Decision Support System (DSS).

Managerial Information
 This type of Information is required by middle management for short and intermediate range
planning which is in terms of months. For example, sales analysis, cash flow projection, and
annual financial statements.
 It is achieved with the aid of Management Information Systems (MIS).
Operational information
 This type of information is required by low management for daily and short term planning to
enforce day-to-day operational activities. For example, keeping employee attendance records,
overdue purchase orders, and current stocks available.
 It is achieved with the aid of Data Processing Systems (DPS).

object modelling: The object modeling techniques is an methodology of object oriented


analysis, design and implementation that focuses on creating a model of objects from the real world
and then to use this model to develop object–oriented software. object modeling technique, OMT was
developed by James Rambaugh.

Phase of OMT
The OMT methodology covers the full software development life cycle. The methodology has
the following phase.
1. Analysis - Analysis is the first phase of OMT methodology. The aim of analysis
phase is to build a model of the real world situation to show its important properties
and domain. This phase is concerned with preparation of precise and correct
modelling of the real world. The analysis phase starts with defining a problem
statement which includes a set of goals. This problem statement is then expanded
into three models; an object model, a dynamic model and a functional model. The
object model shows the static data structure or skeleton of the real world system
and divides the whole application into objects.
2. System design - The system design phase comes after the analysis phase. System
design phase determines the overall system architecture using subsystems,
concurrent tasks and data storage. During system design, the high level structure
of the system is designed. The decisions made during system design are:
o The system is organized in to sub-systems which are then allocated to
processes and tasks, taking into account concurrency and collaboration.
o Persistent data storage is established along with a strategy to manage shared
or global information.
o Boundary situations are checked to help guide trade off priorities.
3. Object design - The object design phase comes after the system design phase is
over. Here the implementation plan is developed. Object design is concerned with
fully classifying the existing and remaining classes, associations, attributes and
operations necessary for implementing a solution to the problem. In object design:
o Operations and data structures are fully defined along with any internal
objects needed for implementation.
o Class level associations are determined.
o Issues of inheritance, aggregation, association and default values are
checked.
4. Implementation - Implementation pahse of the OMT is a matter of translating the
design in to a programming language constructs. It is important to have good
software engineering practice so that the design phase is smoothly translated in to
the implementation phase. Thus while selecting programming language all
constructs should be kept in mind for following noteworthy points.
o To increase flexibility.
o To make amendments easily.
o For the design traceability.
o To increase efficiency.

Object & Classes


Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an instance of
a class.
Class − A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type support.
Links & Associations:
Definition of Link

The logical or physical connection among objects is referred to as link. These links are
used to relate multiple objects and represent a relationship between objects. We can not
reference links, because a link is not a component of either object by its own but do rely
on the objects.

The links in the above example represent the relationship between the different objects.
The links can be of three types – One-to-one, one-to-many, many-to-many.

Definition of Association

A collection of links is specified by an association which have common structure and semantics.
Association is essentially bidirectional. As the class describes the potential objects, in the similar
fashion an association represents a group of possible links.

Comparison Chart

BASIS FOR LINK ASSOCIATION


COMPARISON
Basic A link can be defined as a An association is a specification of a

theoretical and physical connection collection of links.

between objects.

Function Relationship among objects. Connects related classes.

UML design Line segment between objects. Also uses line segment but it shows the

connection between classes.


symbol

Generalization & Inheritance:

Generalization

In the generalization process, the common characteristics of classes are combined to form a class
in a higher level of hierarchy, i.e., subclasses are combined to form a generalized super-class. It
represents an “is – a – kind – of” relationship. For example, “car is a kind of land vehicle”, or
“ship is a kind of water vehicle”.

Specialization
Specialization is the reverse process of generalization. Here, the distinguishing features of groups
of objects are used to form specialized classes from existing classes. It can be said that the
subclasses are the specialized versions of the super-class.
The following figure shows an example of generalization and specialization.
Inheritance: Inheritance is the mechanism that permits new classes to be created out of
existing classes by extending and refining its capabilities. The existing classes are called the base
classes/parent classes/super-classes, and the new classes are called the derived classes/child
classes/subclasses. The subclass can inherit or derive the attributes and methods of the super-
class(es) provided that the super-class allows so. Besides, the subclass may add its own attributes
and methods and may modify any of the super-class methods. Inheritance defines an “is – a”
relationship.
Types of Inheritance
 Single Inheritance − A subclass derives from a single super-class.
 Multiple Inheritance − A subclass derives from more than one super-classes.
 Multilevel Inheritance − A subclass derives from a super-class which in turn is derived from another
class and so on.
 Hierarchical Inheritance − A class has a number of subclasses each of which may have subsequent
subclasses, continuing for a number of levels, so as to form a tree structure.
 Hybrid Inheritance − A combination of multiple and multilevel inheritance so as to form a lattice
structure.
The following figure depicts the examples of different types of inheritance.
Aggregation(‫(تجمع‬:
Aggregation or composition is a relationship among classes by which a class can be made
up of any combination of objects of other classes. It allows objects to be placed directly
within the body of other classes. Aggregation is referred as a “part–of” or “has–a”
relationship, with the ability to navigate from the whole to its parts. An aggregate object
is an object that is composed of one or more other objects.
Example
In the relationship, “a car has–a motor”, car is the whole object or the aggregate, and the
motor is a “part–of” the car. Aggregation may denote −
 Physical containment − Example, a computer is composed of monitor, CPU,
mouse, keyboard, and so on.
 Conceptual containment − Example, shareholder has–a share.

Abstract Classes :An abstract class is a class that is declared abstract—it may
or may not include abstract methods. Abstract classes cannot be instantiated, but they can
be subclassed.

An abstract method is a method that is declared without an implementation (without


braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must be declared abstract, as in:

public abstract class GraphicObject {


// declare fields
// declare nonabstract methods
abstract void draw();}

When an abstract class is subclassed, the subclass usually provides implementations for all
of the abstract methods in its parent class. However, if it does not, then the subclass must
also be declared abstract.

Note: Methods in an interface (see the Interfaces section) that are not declared as default
or static are implicitly abstract, so the abstract modifier is not used with interface methods.
(It can be used, but it is unnecessary.)

Abstract Classes Compared to Interfaces

Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix
of methods declared with or without an implementation. However, with abstract classes, you can
declare fields that are not static and final, and define public, protected, and private concrete
methods. With interfaces, all fields are automatically public, static, and final, and all methods that
you declare or define (as default methods) are public. In addition, you can extend only one class,
whether or not it is abstract, whereas you can implement any number of interfaces.

Which should you use, abstract classes or interfaces?

 Consider using abstract classes if any of these statements apply to your situation:
o You want to share code among several closely related classes.
o You expect that classes that extend your abstract class have many common methods
or fields, or require access modifiers other than public (such as protected and
private).
o You want to declare non-static or non-final fields. This enables you to define
methods that can access and modify the state of the object to which they belong.
 Consider using interfaces if any of these statements apply to your situation:
o You expect that unrelated classes would implement your interface. For example,
the interfaces Comparable and Cloneable are implemented by many unrelated
classes.
o You want to specify the behavior of a particular data type, but not concerned about
who implements its behavior.
o You want to take advantage of multiple inheritance of type.
An Abstract Class Example

In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier
curves, and many other graphic objects. These objects all have certain states (for
example: position, orientation, line color, fill color) and behaviors (for example: moveTo,
rotate, resize, draw) in common. Some of these states and behaviors are the same for all
graphic objects (for example: position, fill color, and moveTo). Others require different
implementations (for example, resize or draw). All GraphicObjects must be able to draw
or resize themselves; they just differ in how they do it. This is a perfect situation for an
abstract superclass. You can take advantage of the similarities and declare all the graphic
objects to inherit from the same abstract parent object (for example, GraphicObject) as
shown in the following figure.

Classes Rectangle, Line, Bezier, and Circle Inherit from GraphicObject

Difference Between Interface and Abstract Class

1. Main difference is methods of a Java interface are implicitly abstract and cannot
have implementations. A Java abstract class can have instance methods that
implements a default behavior.
2. Variables declared in a Java interface is by default final. An abstract class may
contain non-final variables.
3. Members of a Java interface are public by default. A Java abstract class can have
the usual flavors of class members like private, protected, etc..
4. Java interface should be implemented using keyword “implements”; A Java
abstract class should be extended using keyword “extends”.
5. An interface can extend another Java interface only, an abstract class can extend
another Java class and implement multiple Java interfaces.
6. A Java class can implement multiple interfaces but it can extend only one abstract
class.
7. Interface is absolutely abstract and cannot be instantiated; A Java abstract class
also cannot be instantiated, but can be invoked if a main() exists.
8. In comparison with java abstract classes, java interfaces are slow as it requires
extra indirection.

Difference between Classes and Structures

Technically speaking, structs and classes are almost


equivalent, still there are many differences. The major
difference like class provides the flexibility of combining
data and methods (functions ) and it provides the re-usability
called inheritance. Struct should typically be used for
grouping data. The technical difference comes down to subtle
issues about default visibility of members. Here you can see
some of the Difference between Class and Structure.

Class is pass-by-reference and Struct is pass-by-copy, it means that, Class is a reference


type and its object is created on the heap memory where as structure is a value type and its
object is created on the stack memory. More about .... Difference between a Value Type
and a Reference Type

Class can create a subclass that will inherit parent's properties and methods, whereas
Structure does not support the inheritance.

A class has all members private by default. A struct is a class where members
are public by default.

Classes allow to perform cleanup (garbage collector) before object is deallocated because
garbage collector works on heap memory. Objects are usually deallocated when instance
is no longer referenced by other code. Structures can not be garbage collector so no efficient
memory management.

Sizeof empty class is 1 Byte where as Sizeof empty structure is 0 Bytes

Classes are still fit for larger or complex objects and Structs are good
for small, isolated model objects. Boxing and unboxing operations
are used to convert between a struct type and object. Too much
boxing and unboxing can have a negative impact on the heap, the
garbage collector, and ultimately the performance of the application.
In general, it's perfectly possible to create structs that look a lot like classes and classes that
look a lot like structs.

Which style you use depends on circumstances and taste. I usually prefer to use struct for
classes that have all data public. I think of such classes as "not quite proper types, just data
structures."

Section- C
Object oriented programming with C++
difference between C and C++:

1. When compared to C++, C is a subset of C++. All valid C programs are valid C++
programs.
2. C is a structural or procedural programming language, while C++ is an object
oriented programming language.
3. In C, Functions are the fundamental building blocks, while in C++, Objects are the
fundamental building blocks.
4. C doesn't have variable references, while C++ has variable references.
5. C uses malloc and free for memory allocation while C++ uses new and delete for
memory allocation.
6. C does not provide direct support for error handling, while C++ supports exception
handling that helps in error detection and smooth handling.
7. C does not support function and operator overloading, while C++ supports both
function and operator overloading.
8. C doesn't support Generic programming, while templates in C++ allow to write
generic programs.
9. C doesn't support namespaces while C++ supports them.
Difference between C and C++
C C++
C was developed by Dennis Ritchie between C++ was developed by Bjarne Stroustrup in
1969 and 1973 at AT&T Bell Labs. 1979 with C++'s predecessor "C with
Classes".

When compared to C++, C is a subset of C++ is a superset of C. C++ can run most
C++. of C code while C cannot run C++ code.

C supports procedural programming C++ supports both procedural and object


paradigm for code development. oriented programming paradigms; therefore
C++ is also called a hybrid language.

C does not support object oriented Being an object oriented programming


programming; therefore it has no support for language C++ supports polymorphism,
polymorphism, encapsulation, and encapsulation, and inheritance.
inheritance.

In C (because it is a procedural programming In C++ (when it is used as object oriented


language), data and functions are separate programming language), data and functions
and free entities. are encapsulated together in form of an
object. For creating objects class provides a
blueprint of structure of the object.

In C, data are free entities and can be In C++, Encapsulation hides the data to
manipulated by outside code. This is because ensure that data structures and operators are
C does not support information hiding. used as intended.

C, being a procedural programming, it is a While, C++, being an object oriented


function driven language. programming, it is an object driven
language.

C does not support function and operator C++ supports both function and operator
overloading. overloading.

C does not allow functions to be defined inside In C++, functions can be used inside a
structures. structure.

C does not have namespace feature. C++ uses NAMESPACE which avoid
name collisions.
A namespace is a declarative region that
provides a scope to the identifiers (the
names of types, functions, variables, etc)
inside it. Namespaces are used to organize
code into logical groups and to prevent
name collisions that can occur especially
when your code base includes multiple
libraries. All identifiers at namespace scope
are visible to one another without
qualification. Identifiers outside the
namespace can access the members by
using the fully qualified name for each
identifier.
C uses functions for input/output. For C++ uses objects for input output. For
example scanf and printf. example cin and cout.
C does not support reference variables. C++ supports reference variables.

C has no support for virtual and friend C++ supports virtual and friend functions.
functions.
C provides malloc() and calloc()functions for C++ provides new operator for memory
dynamic memory allocation, and free() for allocation and delete operator for memory
memory de-allocation. de-allocation.
C does not provide direct support for error C++ provides support for exception
handling (also called exception handling) handling. Exceptions are used for "hard"
errors that make the code incorrect.

C++ Object Oriented


The prime purpose of C++ programming was to add object orientation to the C programming
language, which is in itself one of the most powerful programming languages.
The core of the pure object-oriented programming is to create an object, in code, that has certain
properties and methods. While designing C++ modules, we try to see whole world in the form of
objects. For example a car is an object which has certain properties such as color, number of
doors, and the like. It also has certain methods such as accelerate, brake, and so on.
There are a few principle concepts that form the foundation of object-oriented programming −

Object
This is the basic unit of object oriented programming. That is both data and function that operate
on data are bundled as a unit called as object.
Class
When you define a class, you define a blueprint for an object. This doesn't actually define any
data, but it does define what the class name means, that is, what an object of the class will consist
of and what operations can be performed on such an object.

Abstraction
Data abstraction refers to, providing only essential information to the outside world and hiding
their background details, i.e., to represent the needed information in program without presenting
the details.
For example, a database system hides certain details of how data is stored and created and
maintained. Similar way, C++ classes provides different methods to the outside world without
giving internal detail about those methods and data.

Encapsulation
Encapsulation is placing the data and the functions that work on that data in the same place. While
working with procedural languages, it is not always clear which functions work on which
variables but object-oriented programming provides you framework to place the data and the
relevant functions together in the same object.

Inheritance
One of the most useful aspects of object-oriented programming is code reusability. As the name
suggests Inheritance is the process of forming a new class from an existing class that is from the
existing class called as base class, new class is formed called as derived class.
This is a very important concept of object-oriented programming since this feature helps to reduce
the code size.

Polymorphism
The ability to use an operator or function in different ways in other words giving different
meaning or functions to the operators or functions is called polymorphism. Poly refers to many.
That is a single function or an operator functioning in many ways different upon the usage is
called polymorphism.

Data Hiding
A key feature of object oriented programming is 'data - hiding' i.e., the data is concealed within a class,
so that it cannot be accessed mistakenly by functions outside the class.
'private' and 'public' are two types of protection available within a class.
Items marked with 'private' can only be accessed by methods defined as part of the class. Data is most
often defined as private.
Private members can be accessed by members of the class.
Public items can be accessed from anywhere in the program without restrictions. Class methods are
usually public. As a general rule, data should not be declared public. Public members can be accessed
by members and objects of the class.
Protected is another type of protection available within a class. Items declared as protected are private
within a class and are available for private access in the derived class. The derived class concept is dealt
with later in this book. The protected access will be discussed again.
Example:
class fact{
int n,fct,temp;
public:
void read_data()
{
printf("Enter the Integer whose factorial you want to find\n");
scanf("%d", &n);
}
void calc_fact()
{
fct=1;
temp=n;
while (n>0)
{
fct=fct*n;
n--;
}
printf("Factorial of %d is %d \n",temp,fct);
}
};
void main()
{
fact f;
clrscr();
f.read_data();
f.calc_fact();
getch();
}
Note: As shown in the above example the variables n, fct and temp are private and can not be accessed
from the main function but can be accessed from the public functions read_data() and calc_data()
C++ Constructor

In C++, constructor is a special method which is invoked automatically at the time of


object creation. It is used to initialize the data members of new object generally. The
constructor in C++ has the same name as class or structure.

There can be two types of constructors in C++.

o Default constructor
o Parameterized constructor

C++ Default Constructor

A constructor which has no argument is known as default constructor. It is invoked at the


time of creating object.

Let's see the simple example of C++ default Constructor.

1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }

Output:

Default Constructor Invoked


Default Constructor Invoked
C++ Parameterized Constructor

A constructor which has parameters is called parameterized constructor. It is used to


provide different values to distinct objects.

Let's see the simple example of C++ Parameterized Constructor.

#include <iostream>
using namespace std;
class Employee {
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void) {
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2=Employee(102, "Nakul", 59000);
e1.display();
e2.display();
return 0;
}

Output:

101 Sonoo 890000


102 Nakul 59000
Constructor Overloading in C++
Prerequisites: Constructors in C++
In C++, We can have more than one constructor in a class with same name, as long as
each has a different list of arguments.This concept is known as Constructor Overloading
and is quite similar to function overloading.
 Overloaded constructors essentially have the same name (name of the class) and
different number of arguments.
 A constructor is called depending upon the number and type of arguments passed.
 While creating the object, arguments must be passed to let compiler know, which
constructor needs to be called.

// C++ program to illustrate int main()

// Constructor overloading {

#include <iostream> // Constructor Overloading

using namespace std; // with two different constructors

class construct // of class name

{ construct o;

public: construct o2( 10, 20);

float area;

// Constructor with no parameters o.disp();

construct(){ o2.disp();

area = 0; } return 1;

// Constructor with two parameters }

construct(int a, int b) { Output:


area = a * b; } 0
void disp(){ 200
cout<< area<< endl; } };

C++ Overloading (Operator and Function)


C++ allows you to specify more than one definition for a function name or an operator in the
same scope, which is called function overloading and operator overloading respectively.
An overloaded declaration is a declaration that is declared with the same name as a previously
declared declaration in the same scope, except that both declarations have different arguments
and obviously different definition (implementation).
When you call an overloaded function or operator, the compiler determines the most appropriate
definition to use, by comparing the argument types you have used to call the function or operator
with the parameter types specified in the definitions. The process of selecting the most appropriate
overloaded function or operator is called overload resolution.
Function Overloading in C++
You can have multiple definitions for the same function name in the same scope. The definition
of the function must differ from each other by the types and/or the number of arguments in the
argument list. You cannot overload function declarations that differ only by return type.
Following is the example where same function print() is being used to print different data types

#include <iostream>
using namespace std; int main(void) {
printData pd;
class printData {
public: // Call print to print integer
void print(int i) { pd.print(5);
cout << "Printing int: " << i << endl;
} // Call print to print float
void print(double f) { pd.print(500.263);
cout << "Printing float: " << f << endl;
} // Call print to print character
void print(char* c) { pd.print("Hello C++");
cout << "Printing character: " << c <<
endl; return 0;
} }
};
When the above code is compiled and executed, it produces the following result −
Printing int: 5
Printing float: 500.263
Printing character: Hello C++

Operators Overloading in C++


You can redefine or overload most of the built-in operators available in C++. Thus, a programmer
can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by the
symbol for the operator being defined. Like any other function, an overloaded operator has a
return type and a parameter list.
Box operator+(const Box&);
declares the addition operator that can be used to add two Box objects and returns final Box
object. Most overloaded operators may be defined as ordinary non-member functions or as class
member functions. In case we define above function as non-member function of a class then we
would have to pass two arguments for each operand as follows −
Box operator+(const Box&, const Box&);
Following is the example to show the concept of operator over loading using a member function.
Here an object is passed as an argument whose properties will be accessed using this object, the
object which will call this operator can be accessed using this operator as explained below −
#include <iostream> Box Box2; // Declare Box2 of type
using namespace std; Box
Box Box3; // Declare Box3 of type
class Box { Box
public: double volume = 0.0; // Store the volume
double getVolume(void) { of a box here
return length * breadth * height;
} // box 1 specification
void setLength( double len ) { Box1.setLength(6.0);
length = len; Box1.setBreadth(7.0);
} Box1.setHeight(5.0);
void setBreadth( double bre ) {
breadth = bre; // box 2 specification
} Box2.setLength(12.0);
void setHeight( double hei ) { Box2.setBreadth(13.0);
height = hei; Box2.setHeight(10.0);
}
// volume of box 1
// Overload + operator to add two Box volume = Box1.getVolume();
objects. cout << "Volume of Box1 : " << volume
Box operator+(const Box& b) { <<endl;
Box box;
box.length = this->length + b.length; // volume of box 2
box.breadth = this->breadth + b.breadth; volume = Box2.getVolume();
box.height = this->height + b.height; cout << "Volume of Box2 : " << volume
return box; <<endl;
}
// Add two object as follows:
private: Box3 = Box1 + Box2;
double length; // Length of a box
double breadth; // Breadth of a box // volume of box 3
double height; // Height of a box volume = Box3.getVolume();
}; cout << "Volume of Box3 : " << volume
<<endl;
// Main function for the program
int main() { return 0;
Box Box1; // Declare Box1 of type }
Box
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
Overloadable/Non-overloadableOperators
Following is the list of operators which can be overloaded −

+ - * / % ^

& | ~ ! , =

< > <= >= ++ --

<< >> == != && ||

+= -= /= %= ^= &=

|= *= <<= >>= [] ()

-> ->* new new [] delete delete []

Following is the list of operators, which can not be overloaded −

:: .* . ?:

Operator Overloading Examples


Here are various operator overloading examples to help you in understanding the concept.
Sr.No Operators & Example

1 Unary Operators Overloading

2 Binary Operators Overloading

3 Relational Operators Overloading

4 Input/Output Operators Overloading

5 ++ and -- Operators Overloading

6 Assignment Operators Overloading

7 Function call () Operator Overloading

8 Subscripting [] Operator Overloading

9 Class Member Access Operator -> Overloading

inline functions : C++ inline function is powerful concept that is commonly used with
classes. If a function is inline, the compiler places a copy of the code of that function at each point
where the function is called at compile time.
Any change to an inline function could require all clients of the function to be recompiled because
compiler would need to replace all the code once again otherwise it will continue with old
functionality.
To inline a function, place the keyword inline before the function name and define the function
before any calls are made to the function. The compiler can ignore the inline qualifier in case
defined function is more than a line.
A function definition in a class definition is an inline function definition, even without the use of
the inline specifier.
Following is an example, which makes use of inline function to return max of two numbers −
#include <iostream>
using namespace std;

inline int Max(int x, int y) {


return (x > y)? x : y;
}

// Main function for the program


int main() {
cout << "Max (20,10): " << Max(20,10) << endl;
cout << "Max (0,200): " << Max(0,200) << endl;
cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;
}
When the above code is compiled and executed, it produces the following result −
Max (20,10): 20
Max (0,200): 200
Max (100,1010): 1010

Virtual Function in C++


A virtual function a member function which is declared within a base class and is re-
defined(Overriden) by a derived class. When you refer to a derived class object using a pointer
or a reference to the base class, you can call a virtual function for that object and execute the
derived class’s version of the function.
 Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for function call.
 They are mainly used to achieve Runtime polymorphism
 Functions are declared with a virtual keyword in base class.
 The resolving of function call is done at Run-time.
Rules for Virtual Functions
1. Virtual functions cannot be static and also cannot be a friend function of another class.
2. Virtual functions should be accessed using pointer or reference of base class type to achieve run
time polymorphism.
3. The prototype of virtual functions should be same in base as well as derived class.
4. They are always defined in base class and overridden in derived class. It is not mandatory for
derived class to override (or re-define the virtual function), in that case base class version of
function is used.
5. A class may have virtual destructor but it cannot have a virtual constructor.
Compile-time(early binding) VS run-time(late binding) behavior of Virtual Functions
Consider the following simple program showing run-time behavior of virtual functions.
Working of virtual functions(concept of VTABLE and VPTR)
As discussed here , If a class contains a virtual function then compiler itself does two things:
1. If object of that class is created then a virtual pointer(VPTR) is inserted as a data member of the
class to point to VTABLE of that class. For each new object created, a new virtual pointer is
inserted as a data member of that class.
2. Irrespective of object is created or not, a static array of function pointer called VTABLE where
each cell contains the address of each virtual function contained in that class.
Consider the example below:

// CPP program to illustrate public:

// working of Virtual Functions void fun_1() { cout << "derived-1\n"; }

#include<iostream> void fun_2() { cout << "derived-2\n"; }

using namespace std; void fun_4(int x) { cout << "derived-4\n"; }

};

class base

{ int main()

public: {

void fun_1() { cout << "base-1\n"; } base *p;

virtual void fun_2() { cout << "base-2\n"; } derived obj1;

virtual void fun_3() { cout << "base-3\n"; } p = &obj1;

virtual void fun_4() { cout << "base-4\n"; }

}; // Early binding because fun1() is non-virtual

// in base

class derived : public base p->fun_1();

{
// Late binding (RTP)

p->fun_2(); // Early binding but this function call is

// illegal(produces error) becasue pointer

// Late binding (RTP) // is of base type and function is of

p->fun_3(); // derived class

//p->fun_4(5);

// Late binding (RTP) }

p->fun_4();

Output:
base-1
derived-2
base-3
base-4

Type of Inheritance
When deriving a class from a base class, the base class may be inherited through public,
protected or private inheritance. The type of inheritance is specified by the access-specifier as
explained above.
We hardly use protected or private inheritance, but public inheritance is commonly used. While
using different type of inheritance, following rules are applied −
 Public Inheritance − When deriving a class from a public base class, publicmembers of the base class
become public members of the derived class and protected members of the base class
become protected members of the derived class. A base class's private members are never accessible
directly from a derived class, but can be accessed through calls to the public and protected members
of the base class.
 Protected Inheritance − When deriving from a protected base class, public and protected members
of the base class become protected members of the derived class.
 Private Inheritance − When deriving from a private base class, public and protected members of the
base class become private members of the derived class.

Multiple Inheritance
A C++ class can inherit members from more than one class and here is the extended syntax −
class derived-class: access baseA, access baseB....
Where access is one of public, protected, or private and would be given for every base class and
they will be separated by comma as shown above. Let us try the following example −
#include <iostream>
using namespace std; class Rectangle: public Shape, public
PaintCost {
// Base class Shape public:
class Shape { int getArea() {
public: return (width * height);
void setWidth(int w) { }
width = w; };
}
void setHeight(int h) { int main(void) {
height = h; Rectangle Rect;
} int area;

protected: Rect.setWidth(5);
int width; Rect.setHeight(7);
int height;
}; area = Rect.getArea();

// Base class PaintCost // Print the area of the object.


class PaintCost { cout << "Total area: " << Rect.getArea() <<
public: endl;
int getCost(int area) {
return area * 70; // Print the total cost of painting
} cout << "Total paint cost: $" <<
}; Rect.getCost(area) << endl;

// Derived class return 0;


}
When the above code is compiled and executed, it produces the following result −
Total area: 35
Total paint cost: $2450

reusable classes : C++ strongly supports the concept of reusability. The C++
classes can be reused in several ways. Once a class has been written and tested, it can be
adapted by another programmer to suit their requirements. This is basically done by
creating new classes, reusing the properties of the existing ones. The mechanism of
deriving a new class from an old one is called inheritance. The old class is referred to as
the base class and the new one is called the derived class or subclass. A derived class
includes all features of the generic base class and then adds qualities specific to the derived
class.

Abstract Classes
An abstract class is, conceptually, a class that cannot be instantiated and is usually
implemented as a class that has one or more pure virtual (abstract) functions.
A pure virtual function is one which must be overridden by any concrete (i.e., non-
abstract) derived class. This is indicated in the declaration with the syntax " = 0" in the
member function's declaration.
Example

class AbstractClass {
public:
virtual void AbstractMemberFunction() = 0; // Pure virtual function makes
// this class Abstract class.
virtual void NonAbstractMemberFunction1(); // Virtual function.

void NonAbstractMemberFunction2();
};

In general an abstract class is used to define an implementation and is intended to be


inherited from by concrete classes. It's a way of forcing a contract between the class
designer and the users of that class. If we wish to create a concrete class (a class that
can be instantiated) from an abstract class we must declare and define a matching
member function for each abstract member function of the base class. Otherwise, if any
member function of the base class is left undefined, we will create a new abstract class
(this could be useful sometimes).
Sometimes we use the phrase "pure abstract class," meaning a class that exclusively
has pure virtual functions (and no data). The concept of interface is mapped to pure
abstract classes in C++, as there is no "interface" construct in C++ the same way that
there is in Java.

Example

class Vehicle {
public:
explicit
Vehicle( int topSpeed )
: m_topSpeed( topSpeed )
{}
int TopSpeed() const {
return m_topSpeed;
}

virtual void Save( std::ostream& ) const = 0;

private:
int m_topSpeed;
};

class WheeledLandVehicle : public Vehicle {


public:
WheeledLandVehicle( int topSpeed, int numberOfWheels )
: Vehicle( topSpeed ), m_numberOfWheels( numberOfWheels )
{}
int NumberOfWheels() const {
return m_numberOfWheels;
}

void Save( std::ostream& ) const; // is implicitly virtual

private:
int m_numberOfWheels;
};

class TrackedLandVehicle : public Vehicle {


public:
TrackedLandVehicle ( int topSpeed, int numberOfTracks )
: Vehicle( topSpeed ), m_numberOfTracks ( numberOfTracks )
{}
int NumberOfTracks() const {
return m_numberOfTracks;
}
void Save( std::ostream& ) const; // is implicitly virtual

private:
int m_numberOfTracks;
};

In this example the Vehicle is an abstract base class as it has an abstract member
function.The class WheeledLandVehicle is derived from the base class. It also
holds data which is common to all wheeled land vehicles, namely the number of
wheels. The class TrackedLandVehicle is another variation of the Vehicle class.
This is something of a contrived example but it does show how that you can share
implementation details among a hierarchy of classes. Each class further refines a
concept. This is not always the best way to implement an interface but in some
cases it works very well. As a guideline, for ease of maintenance and understanding
you should try to limit the inheritance to no more than 3 levels. Often the best set
of classes to use is a pure virtual abstract base class to define a common interface.
Then use an abstract class to further refine an implementation for a set of concrete
classes and lastly define the set of concrete classes.

An abstract class is a class that is designed to be specifically used as a base class.


An abstract class contains at least one pure virtual function. You declare a pure
virtual function by using a pure specifier (= 0) in the declaration of a virtual member
function in the class declaration.
difference between structure and classes:
Maybe I should apologize for going on about C++ yet again, but, following on from the
recent online lecture series that I conducted, I learned that there is a lot of interest in the topic. I
also found the experience a very fruitful source of ideas, inspiration and queries – much of this
will appear here.

During the lectures, I would periodically pose a question, which the attendees could answer via
the chat. An interesting one was: how does a struct differ from a class in C++? …

I will start by defining a struct in C. I would see


it as a customized, composite data type, which
may be constructed from the existing built-in
data types [int, char, etc.], bit fields [integers of
specified bit size] and other structs. This
example shows a simple example of
a struct definition, along with the declaration of
a variable of that type and access to one of the
fields. A struct is a handy and flexible way to
represent data. Similar facilities exist in most
modern programming languages.
How does a C++ class differ from a C struct? There are a few differences. The key ones are:

 A class can also contain functions [called methods].


 The member variables and methods are hidden from the
outside world, unless their declaration follows a public label.
 There can be a pair of special methods – the constructor
and destructor – that are run automatically when an instance of
the class [an object] is created and destroyed.
 Operators to work on the new data type can be defined
using special methods [member functions].
 One class can be used as the basis for the definition of
another [inheritance].
 Declaring a variable of the new type [an instance of the
class; an object] requires just the name of the class – the
keyword class is not required.

Most of these are illustrated in the example here.

But what about a struct in C++? The last example here gives a clue. The only difference
between a struct and class in C++ is the default accessibility of member variables and methods.
In a struct they are public; in a class they are private.

Having imparted this information, I urge you not to exploit it too heavily. A key priority when
you are writing code is to ensure that it is readable [=maintainable]. Somebody – it could be you
– might need to look at this code in a year’s time and understand what it does. I have heard
advice as follows: Assume that the person that will maintain
your code is an armed psychopath, who has limited patience and
knows your home address.
Section- D
Object oriented programming with Java
Introduction to java
Java is a high-level programming language originally developed by Sun Microsystems
and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and
the various versions of UNIX. This tutorial gives a complete understanding of Java. This
reference will take you through simple and practical approaches while learning Java
Programming language.

Why to Learn java Programming?


Java is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Software Development Domain. I will list
down some of the key advantages of learning Java Programming:
 Object Oriented − In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
 Platform Independent − Unlike many other programming languages including C
and C++, when Java is compiled, it is not compiled into platform specific machine,
rather into platform independent byte code. This byte code is distributed over the
web and interpreted by the Virtual Machine (JVM) on whichever platform it is
being run on.
 Simple − Java is designed to be easy to learn. If you understand the basic concept
of OOP Java, it would be easy to master.
 Secure − With Java's secure feature it enables to develop virus-free, tamper-free
systems. Authentication techniques are based on public-key encryption.
 Architecture-neutral − Java compiler generates an architecture-neutral object file
format, which makes the compiled code executable on many processors, with the
presence of Java runtime system.
 Portable − Being architecture-neutral and having no implementation dependent
aspects of the specification makes Java portable. Compiler in Java is written in
ANSI C with a clean portability boundary, which is a POSIX subset.
 Robust − Java makes an effort to eliminate error prone situations by emphasizing
mainly on compile time error checking and runtime checking.
Hello World using Java Programming.
Just to give you a little excitement about Java programming, I'm going to give you a small
conventional C Programming Hello World program, You can try it using Demo link.

Applications of Java Programming


The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java
and its widespread popularity, multiple configurations were built to suit various types of
platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications.
The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java
is guaranteed to be Write Once, Run Anywhere.
 Multithreaded − With Java's multithreaded feature it is possible to write programs
that can perform many tasks simultaneously. This design feature allows the
developers to construct interactive applications that can run smoothly.
 Interpreted − Java byte code is translated on the fly to native machine instructions
and is not stored anywhere. The development process is more rapid and analytical
since the linking is an incremental and light-weight process.
 High Performance − With the use of Just-In-Time compilers, Java enables high
performance.
 Distributed − Java is designed for the distributed environment of the internet.
 Dynamic − Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry extensive
amount of run-time information that can be used to verify and resolve accesses to
objects on run-time.
History: ava was started as a project called "Oak" by James Gosling in June 1991. Gosling's
goals were to implement a virtual machine and a language that had a familiar C-like notation but
with greater uniformity and simplicity than C/C++. The first public implementation was Java 1.0
in 1995. It made the promise of "Write Once, Run Anywhere", with free runtimes on popular
platforms. It was fairly secure and its security was configurable, allowing for network and file
access to be limited. The major web browsers soon incorporated it into their standard
configurations in a secure "applet" configuration. popular quickly. New versions for large and
small platforms (J2EE and J2ME) soon were designed with the advent of "Java 2". Sun has not
announced any plans for a "Java 3".
In 1997, Sun approached the ISO/IEC JTC1 standards body and later the Ecma International to
formalize Java, but it soon withdrew from the process. Java remains a proprietary de facto standard
that is controlled through the Java Community Process. Sun makes most of its Java
implementations available without charge, with revenue being generated by specialized products
such as the Java Enterprise System. Sun distinguishes between its Software Development Kit
(SDK) and Runtime Environment (JRE) which is a subset of the SDK, the primary distinction
being that in the JRE the compiler is not present.
Features of Java
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role in the
popularity of this language. The features of Java are also known as java buzzwords.

A list of most important features of Java language is given below.

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented

Java is an object-oriented programming language. Everything in Java is an object.


Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.

There are two types of platforms software-based and hardware-based. Java provides a
software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms. It has two
components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be run on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms, i.e.,
Write Once and Run Anywhere(WORA).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader : Classloader in Java is a part of the Java Runtime Environment(JRE)


which is used to load Java classes into the Java Virtual Machine dynamically. It
adds security by separating the package for the classes of the local file system
from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
o Security Manager: It determines what resources a class can access such as
reading and writing to the local disk.

Java language provides these securities by default. Some security can also be provided by
an application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust

Robust simply means strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There is automatic garbage collection in java which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All these
points make Java robust.

Architecture-neutral

Java is architecture neutral because there are no implementation dependent features, for
example, the size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4
bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for both
32 and 64-bit architectures in Java.

Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.

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++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
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.

Multi-threaded

A thread is like a separate program, executing concurrently. 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.

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

Java supports dynamic compilation and automatic memory management (garbage


collection).

How Java Differs From C And C++

Introduction to C, C++, and Java :


C is a general-purpose high-level language that was originally developed by Dennis
Ritchie in 1972 for the Unix operating system. C is a successor of B language which was
introduced around 1970. C is a structured language which is easy to learn and produces
efficient programs. it`s a top-down approach. It can handle low-level activities and can be
compiled on a variety of computers. Today C is the most widely used System Programming
Language.
C++ is a general purpose programming language developed by Bjarne Stroustrup starting
in 1979 at Bell Labs, designed to make programming more enjoyable for the serious
programmers.C++ is a superset of the C programming language. In addition to the facilities
provided by C, C++ provides flexible and efficient facilities for defining new types. The
key concept in C++ is class. A class is a user defined type.
Java is a programming language created by James Gosling from Sun Microsystems in
1991. The first publicly available version of Java (Java 1.0) was released in 1995. The Old
name of Java was Oak. Java is now taken by Oracle corporation.The acquisition of Sun
Microsystems by Oracle Corporation was completed by Oracle in January 2010.The
current version of Java is Java 1.7 ( Java 7 ). Java is a Programming language as well as a
Platform itself.
Although Java was modeled after C and C++ languages, it differs from C and C++ in many
ways. Java does not incorporate a number of features available in C and C++. For the
benefit of C and C++ programmers, we point out here a few major differences between
C/C++ and Java language.

Java also adds some new features, while C++ is a superset of C, Java is neither a superset
nor a subset of C or C++.

Java and C
Java is not lot like C but the major difference between Java and C is that Java is an object-
oriented language and has a mechanism to define classes and objects. In an effort to build
a simple and safe language, the Java team did not include some of the C features in Java.

1. Java does not include the C unique statement keywords size of and typedef.
2. Java does not contain the data type struct and union.
3. Java does not define the type modifiers keywords auto, extern, register, signed, and unsigned.
4. Java does not support an explicit pointer type.
5. Java does not have a preprocessor and therefore we cannot use # define, # include, and # ifdef
statements.
6. Java requires that the functions with no arguments must be declared with empty parenthesis
and not with the void keyword as done in C.
7. Java adds new operators such as instanceof and >>>.
8. Java adds labelled break and continue statements.
9. Java adds many features required for object-oriented programming.
C Programming Java Programming

It does include the unique statement keywords It does not include the C unique statement keywords sizeof,
sizeof, and typedef. and typedef.

It contain the data type struct and union. It does not contain the data type struct and union.

It define the type modifiers keywords auto, It does not define the type modifiers keywords auto, extern,
extern, register, signed, and unsigned. register, signed, and unsigned.

It supports an explicit pointer type. It does not support an explicit pointer type.

It has a preprocessor and therefore we can use It does not have a preprocessor and therefore we cannot use
# define, # include, and # ifdef statements. # define, # include, and # ifdef statements.

It requires that the functions with no It requires that the functions with no arguments must be
arguments, with the void keyword declared with empty parenthesis, not with the void keyword

C has no operators such as instanceof and Java adds new operators such as instanceof and >>>.
>>>.

C adds have a break and continue statements. Java adds labeled break and continue statements.

C has no object-oriented programming Java adds many features required for object-oriented
features. programming.

Java and C++


Java is a true object-oriented language while C++ is basically C with object-oriented
extension. That is what exactly the increment operator ++ indicates. C++ has maintained
backward compatibility with C. Is is, therefore, possible to write an old style C program
and run it successfully under C++. Java appears to be similar to C++ when we consider
only the “extensions” part of C++. However, some object -oriented features of C++ make
the C++ code extremely difficult to follow and maintain.
Listed below are some major C++ features that were intentionally omitted from Java or
significantly modified.

1. Java does not support operator overloading.


2. Java does not have template classes as in C++.
3. Java does not support multiple inheritances of classes. This is accomplished using a new feature
called “Interface”.
4. Java does not support global variables. Every variable and method is declared within classes
and forms part of that class.
5. Java does not use pointers.
6. Java has replaced the destructor function with a finalize() function.
7. There are no header files in Java.

C++ Programming Java Programming

It support operator overloading. It does not support operator overloading.

It support has template classes. It does not have template classes as in C++.

It supports multiple inheritances of It does not support multiple inheritances of classes. This is
classes. accomplished using a new feature called “Interface”.

It supports global variables. It does not support global variables. Every variable and method is
declared within classes and forms part of that class.

It supports pointers. It does not use pointers.

It does not support destructor function It has replaced the destructor function with a finalize() function.
with a finalize() function.

There are header files in Java. There are no header files in Java.

Differences among C, C++ and Java Programming Languages: C vs


C++ vs Java
The purpose of learning a programming language is to become a better programmer i.e. to
become more effective at designing and implementing new systems and at maintaining old
ones.
C, C++, and Java are the most popular programming languages used today at a broad level.
They have a pretty similar syntax for basic concepts. Most of the basic constructs like if
statements, loops, function syntax, switch case statements and concepts like recursion are
still valid. Many other concepts like the syntax for comments, and the idea of static class
variables, also held in both Java and C++.
Java uses the syntax of C and structure of C++ language.
Aspects C C++ Java

The developed year 1972 1979 1991

Developed By Dennis Ritchie Bjarne Stroustrup James Gosling


C(Syntax) & C++
Successor of BCPL C
(Structure)

Paradigms Procedural Object Oriented Object Oriented

Platform Dependency Dependent Dependent Independent

50 defined (goto, const


Keywords 32 63
unusable)

Datatypes: union,
Supported Supported Not Supported
structure
Supported (#include, Supported (#include,
Pre-processor directives Not Supported
#define) #define)

Header files Supported Supported Use Packages (import)

Multiple Inheritance not


Inheritance No Inheritance Supported
Supported

Operator Overloading not


Overloading No Overloading Supported
Supported

Pointers Supported Supported No Pointers

Code Translation Compiled Compiled Interpreted

Storage Allocation Uses malloc, calloc Uses new, delete uses garbage collector

Multithreading and
Not Supported Not Supported Supported
Interfaces

Exception Handling No Exception handling Supported Supported

Templates Not Supported Supported Not Supported

Storage class: auto,


Supported Supported Not Supported
extern
No Constructor or
Destructors Supported Not Supported
Destructor

Database Connectivity Not Supported Not Supported Supported

Java and Internet


Java is strongly associated with the internet because of the first application program written
in Java was hot Java.Web browsers to run applets on internet.
Internet users can use Java to create applet programs & run then locally using a Java-
enabled browser such as hot Java.
Java applets have made the internet a true extension of the storage system of the local
computer.

World wide web and Java


1. World wide web is a collection of information stored on internet computers.
2. World wide web is an information retrieval system designed to be used in the
internet’s distributed environment.
3. World wide web contains web pages that provides both information and controls.
4. Web pages contain HTML tags that enable us to find retrieve, manipulate and
display documents world wide.
5. Before Java the world wide web was limited to the display of still images & texts.
6. With the help of Java WWW is capable of supporting animation graphics, games
and wide rage special effects.

7. Java communicate with a web page through a special tag called <applet>.
8. Java user sends a request for an HTML document to the remote computers net
browser.
9. The web-browser is a program that accepts a request, process the request and
sends the required documents.
10. The HTML document is returned to that user browser.
11. The document contains the applet tag which identifies the applet.
12. The corresponding applet is transferred to the user computer.
13. The Java enabled browser on the users computer interprets the byte code and
provide output.

Web Browsers
The internet is a vast sea of information represented in many formants and store on many
computers. a browser is a software application used to locate, retrieve and display content
on the World Wide Web, including Web pages, images, video and other files. As a
client/server model, the browser is the client run on a computer that contacts the Web server
and requests information. The Web server sends the information back to the Web browser
which displays the results.
The browser application retrieves or fetches code, usually written in HTML (HyperText
Markup Language) and/or another language, from a webserver, interprets this code, and
renders (displays) it as a Web page for you to view. on the computer or other Internet-
enabled device that supports a browser.
Example of Web Browsers:
 Hot Java
 Netscape Navigator
 Internet Explorer
 Google Chorme

Java Support System


Internet Connection :local computer should be connected to tne internet
Web Server :A program that accepts request from user and give output as per the
requirement. Apache TomCat server is one of the major web server.
Web Browser :Web browser is a software that will allow you to view web pages on the
internet. it is a program that you use to access the Internet. It reads and knows how to
display and download files that are put on servers for people to read. A program that
provides the acess of WWW and run java applets. Chorme and Firefox are two major web
browers.
HTML:HTML is short for HyperText Markup Language. HTML is used to create
electronic documents (called pages) that are displayed on the World Wide Web. Each page
contains a series of connections to other pages called hyperlinks. Every web page you see
on the Internet is written using one version of HTML code or another.
APPLET tag:The HTML <applet> tag specifies an applet. It is used for embedding a
Java applet within an HTML document. It is not supported in HTML5.
<applet code="Hello.class" width="350" height="350">
</applet>
Java Code :Java code is used for defining java APPLETS
Byte Code :Compiled java code that is refer to in the applet tag and transfer to the user
computer.
Proxy Server :An intermediate server between the requesting client work station and the
original server. It is typically implemented for ensuring security.
Mail Server: A mail server (also known as a mail transfer agent or MTA, a mail transport
agent, a mail router or an Internet mailer) is an application that receives incoming e-mail
from local users (people within the same domain) and remote senders and forwards
outgoing e-mail for delivery.

Simple Java Program


For executing any java program, you need to

o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the java program
o Compile and run the java program

Creating Hello World Example

Let's create the hello java program:

class Simple{
public static void main(String args[]){ System.out.println("Hello Java"); }}

Parameters used in First Java Program

Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().
o class keyword is used to declare a class in java.
o public keyword is an access modifier which represents visibility. It means it is
visible to all.
o static is a keyword. If we declare any method as static, it is known as the static
method. The core advantage of the static method is that there is no need to create
an object to invoke the static method. The main method is executed by the JVM,
so it doesn't require to create an object to invoke the main method. So it saves
memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args is used for command line argument. We will learn it later.
o System.out.println() is used to print statement. Here, System is a class, out is the
object of PrintStream class, println() is the method of PrintStream class. We will
learn about the internal working of System.out.println statement later.

Valid java main method signature

1. public static void main(String[] args) 5. static public void main(String[] args)
2. public static void main(String []args) 6. public static final void main(String[] args)
3. public static void main(String args[]) 7. final public static void main(String[] args)
4. public static void main(String... args) 8. final strictfp public static void main(String[] args)

Invalid java main method signature

1. public void main(String[] args)


2. static void main(String[] args)
3. public void static main(String[] args)
4. abstract public static void main(String[] args)

Class Declaration in Java


Classes are a blueprint for creating individual objects that contain the general characteristics of a defined
object type. A modifier may or may not be used to declare a class.

Syntax
modifier class myClass { //class header
//field, constructor
//method declarations };
Notes
The class body contains constructors for initializing new objects, declarations for the fields that provide
the state of the class and its objects, and methods to implement the behaviour of the class and its objects.
Example
public class Bike {
//fields:
public int speed;
public int gear;
//Constructor:
public Bike(int startSpeed, int startGear) {
this.gear = startGear;
this.speed = startSpeed; }
//Methods:
public void setGear (int newValue) {
this.gear = newValue; }
public void applyBrake(int decrement) {
this.speed -= decrement; }
public void speedUp(int increment) {
this.speed += increment;
}
}

What are braces in Java for?

Braces, also known as curly braces, use { and } to delimit compound statements. Also, Java
uses them for surrounding the bodies of loops, methods and classes.

For example

 Instance initializer, it is a block of code that will execute each time an instance of the class is
created.
class Program {
{ System.out.println("Instance Intializer");
}public static void main(String[] args) {}}
 Static initializer, it is a block of code that will execute only one time when the class is first
loaded.
class Program {
static {
System.out.println("Instance Intializer");
} public static void main(String[] args) {
}}
 A compound statement, it is just a block of code that will execute when the method is invoked.
class Program {
public static void main(String[] args) {
{ ....
System.out.println("Inside method");
.... } }}
 Local variables are declared within code blocks. The scope of a local variable starts at the
variable declaration and ends at the closing curly brace of the containing block.

The main line

is the most important Java method. When you start


public static void main(String[] args)
learning java programming, this is the first method you encounter. Remember the
first Java Hello World program you wrote that runs and prints “Hello World”?
Table of Contents[hide] 1.4 main
1 public static void main(String[] args) 1.5 String[] args
1.1 public 1.6 Java main method command line arguments
in Eclipse
1.2 static
1.3 void

public static void main(String[] args)

Java main method is the entry point of any java program. Its syntax is always public
static void main(String[] args) . You can only change the name of String array argument, for
example you can change args to myStringArgs.
Also String array argument can be written as String... args or String args[].

Let’s look at the java main method closely and try to understand each of its parts.

public

This is the access modifier of the main method. It has to be public so that java runtime
can execute this method. Remember that if you make any method non-public then it’s
not allowed to be executed by any program, there are some access restrictions applied.
So it means that the main method has to be public. Let’s see what happens if we
define the main method as non-public.
public class Test { static void main(String[] args){ System.out.println("Hello World"); } }
$ javac Test.java
$ java Test
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application $

static

When java runtime starts, there is no object of the class present. That’s why the main
method has to be static so that JVM can load the class into memory and call the main
method. If the main method won’t be static, JVM would not be able to call it because
there is no object of the class is present. Let’s see what happens when we remove
static from java main method.

public class Test {


public void main(String[] args){
System.out.println("Hello World");}}
$ javac Test.java
$ java Test
Error: Main method is not static in class Test, please define the main method as:
public static void main(String[] args) $

void
Java programming mandates that every method provide the return type. Java main
method doesn’t return anything, that’s why it’s return type is void. This has been done
to keep things simple because once the main method is finished executing, java
program terminates. So there is no point in returning anything, there is nothing that
can be done for the returned object by JVM. If we try to return something from the
main method, it will give compilation error as an unexpected return value. For
example, if we have the main method like below.
public class Test {
public static void main(String[] args){
return 0;}}

We get below error when above program is compiled.


$ javac Test.java
Test.java:5: error: incompatible types: unexpected return value
return 0; ^
1 error $
main

This is the name of java main method. It’s fixed and when we start a java program, it
looks for the main method. For example, if we have a class like below.

public class Test {


public static void mymain(String[] args){
System.out.println("Hello World");}}
And we try to run this program, it will throw an error that the main method is not
found.

$ javac Test.java
$ java Test
Error: Main method not found in class Test, please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application $

String[] args

Java main method accepts a single argument of type String array. This is also called as
java command line arguments. Let’s have a look at the example of using java
command line arguments.

public class Test {


public static void main(String[] args){
for(String s : args){
System.out.println(s);}}}

Above is a simple program where we are printing the command line arguments. Let’s
see how to pass command line arguments when executing above program.

$ javac Test.java
$ java Test 1 2 3
1
2
3
$ java Test "Hello World" "Pankaj Kumar"
Hello World
Pankaj Kumar
$ java Test
$
Java Output
You can simply use System.out.println(), System.out.print() or System.out.printf() to send output to
standard output (screen).
System is a class and out is a public static field which accepts output data. Don't worry if you don't
understand it. Classes, public, and static will be discussed in later chapters.

Let's take an example to output a line.

1. class AssignmentOperator {
2. public static void main(String[] args) {
3.
4. System.out.println("Java programming is interesting.");
5. }
6. }

Implementing a Java Program

Implementing Java Program


Implementation of a Java application program involves a series of steps. They include :

 Creating the program


 Compiling the program
 Running the program
Creating the program
We can create a program using any text editor. Assume that we have entered the
following program :

class Javaapp { public static void main(String[] args) {


System.out.println("hajsoftutorial");}}

We must save this program in a file called Javaapp.java ensuring that the file name
contains the class name properly. This file is called the source file. Note that all Java
source files will have the extension java.

Compiling the program


To compile the program, we must run the Java Compiler javac, with the name of the
source file on the command line as shown below :
If everything is OK, the javac compiler creates a file called Javaapp.class containing
the bytecodes of the program. Note that the compiler automatically names the bytecode
file as <classname>.class.
Running the program
To run the program, we must run the Java interpreter java, with the name of the class file
on the command line as shown below :
Now, the interpreter looks for the main method in the program and begins execution from
there. Note that we simply type “Javaapp” at the command line and not “Javaapp.class”
or “Javaapp.java“.
Machine neutral
Machine Neutral Platform Independent means that while writing the program in java, we don't
need to care about on which Machine or platform the program will going to be executed. Like in
C language if we want to run the program in Windows XP the we need to write the program in
windows compatible C compiler and in windows platform to c program in UNIX or Linux we need
to edit and compile the same program in Linux and UNIX compatible compiler and environment.

Java breaks all these restriction, Java gives the freedom to write and compile the program
in any platform or machine and the same program can run on different platform and
machine. Example Java program written for Linux system can also run on windows and
UNIX etc.

The secret behind Architectural Neutral of java is JAVA VIRTUAL MACHINE.


All language compilers translate source code into machine code for a specific computer. Java
compiler also does the same thing. Then, how does java achieve architecture neutrality? The
answer is that the Java compiler produces an intermediate code known as byte-code for a machine
that does not exits. This machine is called the Java Virtual Machine and it exits only inside the
computer memory. It is a simulated computer within the computer and does all major functions of
a real computer.
Java Virtual Machine
JVM is a engine that provides runtime environment to drive the Java Code or
applications. It converts Java bytecode into machines language. JVM is a part of
JRE(Java Run Environment). It stands for Java Virtual Machine

 In other programming languages, the compiler produces machine code for a


particular system. However, Java compiler produces code for a Virtual
Machine known as Java Virtual Machine.
 First, Java code is complied into bytecode. This bytecode gets interpreted on
different machines
 Between host system and Java source, Bytecode is an intermediary language.
 JVM is responsible for allocating memory space.

What it does
The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.

JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded
first by the classloader. There are three built-in classloaders in Java.

1. Bootstrap ClassLoader : This is the first classloader which is the super class of Extension classloader. It
loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes,
java.net package classes, java.util package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System
classloader. It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the
classfiles from classpath. By default, classpath is set to current directory. You can change the classpath
using "-cp" or "-classpath" switch. It is also known as Application classloader.

1. //Let's see an example to print the classloader name


2. public class ClassLoaderExample
3. {
4. public static void main(String[] args)
5. {
6. // Let's print the classloader name of current class.
7. //Application/System classloader will load this class
8. Class c=ClassLoaderExample.class;
9. System.out.println(c.getClassLoader());
10. //If we print the classloader name of String, it will print null because it is an
11. //in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader
12. System.out.println(String.class.getClassLoader());
13. }
14. }
Test it Now

Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your own classloader, you need to extend
the ClassLoader class.

2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the code for
methods.

3) Heap
It is the runtime data area in which objects are allocated.

4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and
return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.

6) Native Method Stack


It contains all the native methods used in the application.

7) Execution Engine
It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code
that have similar functionality at the same time, and hence reduces the amount of time needed for
compilation. Here, the term "compiler" refers to a translator from the instruction set of a Java virtual
machine (JVM) to the instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate with another application
written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to the Console or
interact with OS libraries.

Command Line Arguments


Command Line Argument is information passed to the program when you run the
program. The passed information is stored as a string array in the main method. Later,
you can use the command line arguments in your program.

Example While running a class Demo, you can specify command line arguments as

Command Line Arguments in Java: Important Points

 Command Line Arguments can be used to specify configuration information


while launching your application.
 There is no restriction on the number of java command line arguments.You can
specify any number of arguments
 Information is passed as Strings.
 They are captured into the String args of your main method
 Example: To Learn java Command Line Arguments
 Step 1) Copy the following code into an editor.

class Demo{

public static void main(String b[]){

System.out.println("Argument one = "+b[0]);

System.out.println("Argument two = "+b[1]);}}

 Step 2) Save & Compile the code

Step 3) Run the code as java Demo apple orange.


 Step 4) You must get an output as below.

An application with Two Classes


Java Program Structure

Section Description

Documentation You can write a comment in this section. Comments are beneficial for
Section the programmer because they help them understand the code. These
are optional, but we suggest you use them because they are useful to
understand the operation of the program, so you must write comments
within the program.

Package You can create a package with any name. A package is a group of
statement classes that are defined by a name. That is, if you want to declare many
classes within one element, then you can declare it within a package. It
is an optional part of the program, i.e., if you do not want to declare any
package, then there will be no problem with it, and you will not get any
errors. Here, the package is a keyword that tells the compiler that
package has been created.It is declared as:

package package_name;

Import This line indicates that if you want to use a class of another package,
statements then you can do this by importing it directly into your program.
Example:import calc.add;

Interface Interfaces are like a class that includes a group of method declarations.
statement It's an optional section and can be used when programmers want to
implement multiple inheritances within a program.

Class A Java program may contain several class definitions. Classes are the
Definition main and essential elements of any Java program.
Main Method Every Java stand-alone program requires the main method as the
Class starting point of the program. This is an essential part of a Java
program. There may be many classes in a Java program, and only one
class defines the main method. Methods contain data type declaration
and executable statements.
public class Hello{
/* Author: www.w3schools.in Writes the words "Hello Java" on the screen */
public static void main(String[] args){
System.out.println("Hello Java"); }
Let's Look into Various Parts of the Above Java Program

public class Hello  This creates a class called Hello.


 All class names must start with a capital letter.
 The public word means that it is accessible from any other classes.

/* Comments */ The compiler ignores comment block. Comment can be used anywhere in the
program to add info about the program or code block, which will be helpful for
developers to understand the existing code in the future easily.

Braces Two curly brackets {...} are used to group all the commands, so it is known that the
commands belong to that class or method.

public static void  When the main method is declared public, it means that it can also be used by
main code outside of its class, due to which the main method is declared public.
 The word static used when we want to access a method without creating its
object, as we call the main method, before creating any class objects.
 The word void indicates that a method does not return a value. main() is declared
as void because it does not return a value.
 main is a method; this is a starting point of a Java program.

You will notice that the main method code has been moved to some spaces
left. It is called indentation which used to make a program easier to read and
understand.

String[] args It is an array where each element of it is a string, which has been named as "args".
If your Java program is run through the console, you can pass the input parameter,
and main() method takes it as input.
System.out.println(); This statement is used to print text on the screen as output, where the system is a
predefined class, and out is an object of the PrintWriter class defined in the system.
The method println prints the text on the screen with a new line. You can also
use print() method instead of println() method. All Java statement ends with a
semicolon.

Java Program Structure: A Java program consists of different sections. Some of them
are mandatory but some are optional. The optional section can be excluded from the
program depending upon the requirements of the programmer.
Documentation Section
It includes the comments to tell the program's purpose. It improves the readability of the
program.
Package Statement
It includes statement that provides a package declaration.
Import statements
It includes statements used for referring classes and interfaces that are declared in other
packages.
Interface Section
It is similar to a class but only includes constants, method declaration.
Class Section
It describes information about user defines classes present in the program. Every Java
program consists of at least one class definition. This class definition declares the main
method. It is from where the execution of program actually starts.
1. Documentation Section: It includes the comments that improve the readability of the
program. A comment is a non-executable statement that helps to read and understand a
program especially when your programs get more complex. It is simply a message that
exists only for the programmer and is ignored by the compiler. A good program should
include comments that describe the purpose of the program, author name, date and time of
program creation. This section is optional and comments may appear anywhere in the
program.
Java programming language supports three types of comments.
Single line (or end-of line) comment: It starts with a double slash symbol (//) and
terminates at the end of the current line. The compiler ignores everything from // to the end
of the line. For example:
// Calculate sum of two numbers
Multiline Comment: Java programmer can use C/C++ comment style that begins with
delimiter /* and ends with */. All the text written between the delimiter is ignored by the
compiler. This style of comments can be used on part of a line, a whole line or more
commonly to define multi-line comment. For example.
/*calculate sum of two numbers */
Comments cannot be nested. In other words, you cannot comment a line that already
includes traditional comment. For example,
/* x = y /* initial value */ + z; */ is wrong.
Documentation comments: This comment style is new in Java. Such comments begin
with delimiter /** and end with */. The compiler also ignores this type of comments just
like it ignores comments that use / * and */. The main purpose of this type of comment is
to automatically generate program documentation. The java doc tool reads these comments
and uses them to prepare your program's documentation in HTML format. For example.
/**The text enclosed here will be part of program documentation */
Package Statement: Java allows you to group classes in a collection known as package.
A package statement includes a statement that provides a package declaration. It must
appear as the first statement in the source code file before any class or interface declaration.
This statement is optional. For example: Suppose you write the following package
declaration as the first statement in the source code file.
package employee;
This statement declares that all classes and interfaces defined in this source file are part of
the employee package. Only one package declaration can appear in the source file.
Import Statement: Java contains many predefined classes that are stored into packages.
In order to refer these standard predefined classes in your program, you need to use fully
qualified name (i.e. Packagename.className). But this is a very tedious task as one need
to retype the package path name along with the classname. So a better alternative is to use
an import statement.
An import statement is used for referring classes that are declared in other packages. The
import statement is written after a package statement but before any class definition. You
can import a specific class or all the classes of the package. For example : If you want to
import Date class of java.util package using import statement then write
import java.util.Date;
This statement allows the programmer to use the simple classname Date rather than fully
qualified classname java.util.Date in the code.
Unlike package statement, you can specify more than one import statement in your
program.
For example:
Import java.util.Date; /* imports only the Date class in java.util package */
import java.applet.*; // imports all the classes in java applet
// package
Interface Section: In the interface section, we specify the interfaces. An interface is similar
to a class but contains only constants and method declarations. Interfaces cannot be
instantiated. They can only be implemented by classes or extended by other interfaces. It
is an optional section and is used when we wish to implement multiple inheritance feature
in the program.
interface stack {
void push(int item); // Insert item into stack
int pop(); // Delete an item from stack
}
Class Section: The Class section describes the information about user-defined classes
present in the program. A class is a collection of fields (data variables) and methods that
operate on the fields. Every program in Java consists of at least one class, the one that
contains the main method. The main () method which is from where the execution of
program actually starts and follow the statements in the order specified.
The main method can create objects, evaluate expressions, and invoke other methods and
much more. On reaching the end of main, the program terminates and control passes back
to the operating system.
The class section is mandatory.
After discussing the structure of programs in Java, we shall now discuss a program that
displays a string Hello Java on the screen.
// Program to display message on the screen
class HelloJava {
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Program'sExplanation:
1. The first line of the program begins with //, indicating that the remainder of the line is a
comment. It describes the purpose of the program.
2. Since Java is an object-oriented language, so everything in a Java program resides inside
a class. In our program, the second line
classFirstProg
defines a class named FirstProg. The keyword class before the class name identifies that it
is a class definition. By convention, begin the class name with an uppercase letter and each
subsequent word in a class name with an uppercase letter. The naming of the class must
follow the same rules as for naming of any other identifier.
3. The opening curly brace ({) after the class name as in line 3 tells the compiler from
where does the body of the class begin. The closing curly brace (}) in line 8 tells the
compiler where does the body of class ends. Any code between these braces is considered
to be part of FirstProg class. Note that lines between these braces are indented which is
considered a good programming practice.
4. The lines 4 through 7 defines a method main () of the FirstProg class which serves as
the entry point for the program execution. A method contains a collection of programming
instructions that describe how to carry out a particular task. Line 4 specifies the main ()
method header which must always be written as
public static void main(String[] args)
We shall now discuss the various terms used in the method header,
• public: The public keyword is an access specifier which indicates that the method
declared here should have public access, i.e. anyone can invoke it such as Java Virtual
Machine (JVM). All Java programs must have at least one class that declares a public
method named main. The JVM will start the execution of the program at the first statement
of the main method and terminates execution after the last statement.
• static: The keyword static allows main () to called before an object of the class has
created. This is necessary since main () is called by the JVM before any objects are made.
Since it is static, it can be invoked directly from a class.
• void: The type modifier void indicates that the main () method is declared does not return
a value.
• string [] args: The argument String [] args is the only parameter in the main method. The
String [] args declares a parameter named args which contains an array of objects of the
class type String. The args receive any command-line arguments present when the program
executed.
5. The code for the main method appears between the pair of curly braces. In our program,
this method contains only one executable statement.
System.out.println("Welcome to Java");
This statement displays a message Welcome to Java in the command window.
This statement might look a little confusing the first time so to help make things clearer
let's examine the statement from left to right.
• System: It is the name of the standard class that contain objects that encapsulates the
standard I/O devices for your system. It contained in the package java.lang. Since java.lang
is imported in every Java program by default; therefore the java.lang is the
only package in the Java API that does not require an import declaration.
• out: The object out represents the standard output stream (i.e. command window) and is
a static data member of the class System. To refer the out member of the System class write
System.out.
• println(): The println() is the method of out object that takes the text string as an argument
and displays it to the standard output, i.e. monitor's screen. It then terminates the output
line so that each call to println () displays its output on a new line.
A method is invoked by supplying an object reference (in this case System. out) and a
method name (println() ) separated by the dot(.). It demonstrates one way in which you can
call a class method.
The semicolon at the end of this statement specifies the end of the statement. Every
statement in Java must end with a semicolon (;).
On executing this Java program, a message Welcome to Java would be displayed on the
screen.
NOTE: In addition to println() method, System.out also has a print() method that displays
a string but unlike println() method, the cursor does not move to the beginning of the next
line after displaying the string.

You might also like