What Is UML: Ii Unit

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 37

II UNIT

UML (Unified Modeling Language) is a general-purpose, graphical modeling language in the field
of Software Engineering. UML is used to specify, visualize, construct, and document the artifacts
(major elements) of the software system. It was initially developed by Grady Booch, Ivar Jacobson,
and James Rumbaugh in 1994-95 at Rational software, and its further development was carried out
through 1996. In 1997, it got adopted as a standard by the Object Management Group.
UML (Unified Modeling Language) is a general-purpose, graphical modeling language in the field
of Software Engineering. UML is used to specify, visualize, construct, and document the artifacts
(major elements) of the software system. It was initially developed by Grady Booch, Ivar Jacobson,
and James Rumbaugh in 1994-95 at Rational software, and its further development was carried out
through 1996. In 1997, it got adopted as a standard by the Object Management Group.

What is UML
The UML stands for Unified modeling language, is a standardized general-purpose visual modeling
language in the field of Software Engineering. It is used for specifying, visualizing, constructing,
and documenting the primary artifacts of the software system. It helps in designing and
characterizing, especially those software systems that incorporate the concept of Object orientation.
It describes the working of both the software and hardware systems.
The UML was developed in 1994-95 by Grady Booch, Ivar Jacobson, and James Rumbaugh at the
Rational Software. In 1997, it got adopted as a standard by the Object Management Group (OMG).
The Object Management Group (OMG) is an association of several companies that controls the
open standard UML. The OMG was established to build an open standard that mainly supports the
interoperability of object-oriented systems. It is not restricted within the boundaries, but it can also
be utilized for modeling the non-software systems. The OMG is best recognized for the Common
Object Request Broker Architecture (CORBA) standards.

Goals of UML
 Since it is a general-purpose modeling language, it can be utilized by all the modelers.
 UML came into existence after the introduction of object-oriented concepts to systemize and
consolidate the object-oriented development, due to the absence of standard methods at that
time.
 The UML diagrams are made for business users, developers, ordinary people, or anyone
who is looking forward to understand the system, such that the system can be software or
non-software.
 Thus it can be concluded that the UML is a simple modeling approach that is used to model
all the practical systems.

Characteristics of UML
The UML has the following features:
 It is a generalized modeling language.
 It is distinct from other programming languages like C++, Python, etc.
 It is interrelated to object-oriented analysis and design.
 It is used to visualize the workflow of the system.
 It is a pictorial language, used to generate powerful modeling artifacts.

Conceptual Modeling
Before moving ahead with the concept of UML, we should first understand the basics of the
conceptual model.
A conceptual model is composed of several interrelated concepts. It makes it easy to understand the
objects and how they interact with each other. This is the first step before drawing UML diagrams.
Following are some object-oriented concepts that are needed to begin with UML:
 Object: An object is a real world entity. There are many objects present within a single
system. It is a fundamental building block of UML.
 Class: A class is a software blueprint for objects, which means that it defines the variables
and methods common to all the objects of a particular type.
 Abstraction: Abstraction is the process of portraying the essential characteristics of an
object to the users while hiding the irrelevant information. Basically, it is used to envision
the functioning of an object.
 Inheritance: Inheritance is the process of deriving a new class from the existing ones.
 Polymorphism: It is a mechanism of representing objects having multiple forms used for
different purposes.
 Encapsulation: It binds the data and the object together as a single unit, enabling tight
coupling between them.

OO Analysis and Design


OO is an analysis of objects, and design means combining those identified objects. So, the main
purpose of OO analysis is identifying the objects for designing a system. The analysis can also be
done for an existing system. The analysis can be more efficient if we can identify the objects. Once
we have identified the objects, their relationships are then identified, and the design is also
produced.
The purpose of OO is given below:
 To identify the objects of a system.
 To identify their relationships.
 To make a design that is executable when the concepts of OO are employed.
Following are the steps where OO concepts are applied and implemented:
Step 1: OO Analysis
The main purpose of OO analysis is identifying the objects and describing them correctly. After the
objects are identified, the designing step is easily carried out. It is a must to identify the objects with
responsibilities. Here the responsibility refers to the functions performed by the objects. Each
individual object has its own functions to perform. The purpose of the system is fulfilled by
collaborating these responsibilities.
Step 2: OO Design
This phase mainly emphasizes on meeting the requirements. In this phase, the objects are joined
together as per the intended associations. After the association is completed, the designing phase
also gets complete.
Step 3: OO Implementation
This is the last phase that comes after the designing is done. It implements the design using any OO
languages like C++, Java, etc.

Role of UML in OO design


As the UML is a modeling language used to model software as well as non-software systems, but
here it focuses on modeling OO software applications. It is essential to understand the relation
between the OO design and UML. The OO design can be converted into the UML as and when
required. The OO languages influence the programming world as they model real world objects.
The UML itself is an amalgamation of object-oriented notations like Object-Oriented Design
(OOD), Object Modeling Technique (OMT), and Object-Oriented Software Engineering (OOSE).
The strength of these three approaches is utilized by the UML to represent more consistency.

UML-Building Blocks
UML is composed of three main building blocks, i.e., things, relationships, and diagrams. Building
blocks generate one complete UML model diagram by rotating around several different blocks. It
plays an essential role in developing UML diagrams. The basic UML building blocks are enlisted
below:
1. Things
2. Relationships
3. Diagrams

Things
Anything that is a real world entity or object is termed as things. It can be divided into several
different categories:
 Structural things
 Behavioral things
 Grouping things
 Annotational things
Structural things
Nouns that depicts the static behavior of a model is termed as structural things. They display the
physical and conceptual components. They include class, object, interface, node, collaboration,
component, and a use case.
Class: A Class is a set of identical things that outlines the functionality and properties of an object.
It also represents the abstract class whose functionalities are not defined. Its notation is as follows

Object:: An individual that describes the behavior and the functions of a system. The notation of
the object is similar to that of the class; the only difference is that the object name is always
underlined and its notation is given below;

Interface: A set of operations that describes the functionality of a class, which is implemented
whenever an interface is implemented.
Collaboration: It represents the interaction between things that is done to meet the goal. It is
symbolized as a dotted ellipse with its name written inside it.

Use case: Use case is the core concept of object-oriented modeling. It portrays a set of actions
executed by a system to achieve the goal.

Actor: It comes under the use case diagrams. It is an object that interacts with the system, for
example, a user.

Component: It represents the physical part of the system.

Node: A physical element that exists at run time.


Behavioral Things
They are the verbs that encompass the dynamic parts of a model. It depicts the behavior of a system.
They involve state machine, activity diagram, interaction diagram, grouping things, annotation
things
State Machine: It defines a sequence of states that an entity goes through in the software
development lifecycle. It keeps a record of several distinct states of a system component.

Activity Diagram: It portrays all the activities accomplished by different entities of a system. It is
represented the same as that of a state machine diagram. It consists of an initial state, final state, a
decision box, and an action notation.
Interaction Diagram: It is used to envision the flow of messages between several components in a
system.
Grouping Things
It is a method that together binds the elements of the UML model. In UML, the package is the only
thing, which is used for grouping.
Package: Package is the only thing that is available for grouping behavioral and structural things.

Annotation Things
It is a mechanism that captures the remarks, descriptions, and comments of UML model elements.
In UML, a note is the only Annotational thing.
Note: It is used to attach the constraints, comments, and rules to the elements of the model. It is a
kind of yellow sticky note.

Relationships
It illustrates the meaningful connections between things. It shows the association between the
entities and defines the functionality of an application. There are four types of relationships given
below:
Dependency: Dependency is a kind of relationship in which a change in target element affects the
source element, or simply we can say the source element is dependent on the target element. It is
one of the most important notations in UML. It depicts the dependency from one entity to another.
It is denoted by a dotted line followed by an arrow at one side as shown below,

Association: A set of links that associates the entities to the UML model. It tells how many
elements are actually taking part in forming that relationship.
It is denoted by a dotted line with arrowheads on both sides to describe the relationship with the
element on both sides.

Generalization: It portrays the relationship between a general thing (a parent class or superclass)
and a specific kind of that thing (a child class or subclass). It is used to describe the concept of
inheritance.
It is denoted by a straight line followed by an empty arrowhead at one side.

Realization: It is a semantic kind of relationship between two things, where one defines the
behavior to be carried out, and the other one implements the mentioned behavior. It exists in
interfaces.
It is denoted by a dotted line with an empty arrowhead at one side.

Diagrams
The diagrams are the graphical implementation of the models that incorporate symbols and text.
Each symbol has a different meaning in the context of the UML diagram. There are thirteen
different types of UML diagrams that are available in UML 2.0, such that each diagram has its own
set of a symbol. And each diagram manifests a different dimension, perspective, and view of the
system.
UML diagrams are classified into three categories that are given below:
1. Structural Diagram
2. Behavioral Diagram
3. Interaction Diagram
Structural Diagram: It represents the static view of a system by portraying the structure of a
system. It shows several objects residing in the system. Following are the structural diagrams given
below:
 Class diagram
 Object diagram
 Package diagram
 Component diagram
 Deployment diagram
Behavioral Diagram: It depicts the behavioral features of a system. It deals with dynamic parts of
the system. It encompasses the following diagrams:
 Activity diagram
 State machine diagram
 Use case diagram
Interaction diagram: It is a subset of behavioral diagrams. It depicts the interaction between two
objects and the data flow between them. Following are the several interaction diagrams in UML:
 Timing diagram
 Sequence diagram
 Collaboration diagram

UML- Architecture
Software architecture is all about how a software system is built at its highest level. It is needed to
think big from multiple perspectives with quality and design in mind. The software team is tied to
many practical concerns, such as:
 The structure of the development team.
 The needs of the business.
 Development cycle.
 The intent of the structure itself.
Software architecture provides a basic design of a complete software system. It defines the elements
included in the system, the functions each element has, and how each element relates to one
another. In short, it is a big picture or overall structure of the whole system, how everything works
together.
To form an architecture, the software architect will take several factors into consideration:
 What will the system be used for?
 Who will be using the system?
 What quality matters to them?
 Where will the system run?
The architect plans the structure of the system to meet the needs like these. It is essential to have
proper software architecture, mainly for a large software system. Having a clear design of a
complete system as a starting point provides a solid basis for developers to follow.
Each developer will know what needs to be implemented and how things relate to meet the desired
needs efficiently. One of the main advantages of software architecture is that it provides high
productivity to the software team. The software development becomes more effective as it comes up
with an explained structure in place to coordinate work, implement individual features, or ground
discussions on potential issues. With a lucid architecture, it is easier to know where the key
responsibilities are residing in the system and where to make changes to add new requirements or
simply fixing the failures.
In addition, a clear architecture will help to achieve quality in the software with a well-designed
structure using principles like separation of concerns; the system becomes easier to maintain, reuse,
and adapt. The software architecture is useful to people such as software developers, the project
manager, the client, and the end-user. Each one will have different perspectives to view the system
and will bring different agendas to a project. Also, it provides a collection of several views. It can
be best understood as a collection of five views:
1. Use case view
2. Design view
3. Implementation view
4. Process view
5. Development view

Use case view


 It is a view that shows the functionality of the system as perceived by external actors.
 It reveals the requirements of the system.
 With UML, it is easy to capture the static aspects of this view in the use case diagrams,
whereas it?s dynamic aspects are captured in interaction diagrams, state chart diagrams, and
activity diagrams.
Design View
 It is a view that shows how the functionality is designed inside the system in terms of static
structure and dynamic behavior.
 It captures the vocabulary of the problem space and solution space.
 With UML, it represents the static aspects of this view in class and object diagrams, whereas
its dynamic aspects are captured in interaction diagrams, state chart diagrams, and activity
diagrams.

Implementation View
 It is the view that represents the organization of the core components and files.
 It primarily addresses the configuration management of the system?s releases.
 With UML, its static aspects are expressed in component diagrams, and the dynamic aspects
are captured in interaction diagrams, state chart diagrams, and activity diagrams.

Process View
 It is the view that demonstrates the concurrency of the system.
 It incorporates the threads and processes that make concurrent system and synchronized
mechanisms.
 It primarily addresses the system's scalability, throughput, and performance.
 Its static and dynamic aspects are expressed the same way as the design view but focus more
on the active classes that represent these threads and processes.

Deployment View
 It is the view that shows the deployment of the system in terms of physical architecture.
 It includes the nodes, which form the system hardware topology where the system will be
executed.
 It primarily addresses the distribution, delivery, and installation of the parts that build the
physical system.

UML-Diagrams
The UML diagrams are categorized into structural diagrams, behavioral diagrams, and also
interaction overview diagrams. The diagrams are hierarchically classified in the following figure:
1. Structural Diagrams
Structural diagrams depict a static view or structure of a system. It is widely used in the
documentation of software architecture. It embraces class diagrams, composite structure diagrams,
component diagrams, deployment diagrams, object diagrams, and package diagrams. It presents an
outline for the system. It stresses the elements to be present that are to be modeled.
 Class Diagram: Class diagrams are one of the most widely used diagrams. It is the
backbone of all the object-oriented software systems. It depicts the static structure of the
system. It displays the system's class, attributes, and methods. It is helpful in recognizing the
relation between different objects as well as classes.
 Composite Structure Diagram: The composite structure diagrams show parts within the
class. It displays the relationship between the parts and their configuration that ascertain the
behavior of the class. It makes full use of ports, parts, and connectors to portray the internal
structure of a structured classifier. It is similar to class diagrams, just the fact it represents
individual parts in a detailed manner when compared with class diagrams.
 Object Diagram: It describes the static structure of a system at a particular point in time. It
can be used to test the accuracy of class diagrams. It represents distinct instances of classes
and the relationship between them at a time.
 Component Diagram: It portrays the organization of the physical components within the
system. It is used for modeling execution details. It determines whether the desired
functional requirements have been considered by the planned development or not, as it
depicts the structural relationships between the elements of a software system.
 Deployment Diagram: It presents the system's software and its hardware by telling what
the existing physical components are and what software components are running on them. It
produces information about system software. It is incorporated whenever software is used,
distributed, or deployed across multiple machines with dissimilar configurations.
 Package Diagram: It is used to illustrate how the packages and their elements are
organized. It shows the dependencies between distinct packages. It manages UML diagrams
by making it easily understandable. It is used for organizing the class and use case diagrams.

2. Behavioral Diagrams:
Behavioral diagrams portray a dynamic view of a system or the behavior of a system, which
describes the functioning of the system. It includes use case diagrams, state diagrams, and activity
diagrams. It defines the interaction within the system.
 State Machine Diagram: It is a behavioral diagram. it portrays the system's behavior
utilizing finite state transitions. It is also known as the State-charts diagram. It models the
dynamic behavior of a class in response to external stimuli.
 Activity Diagram: It models the flow of control from one activity to the other. With the
help of an activity diagram, we can model sequential and concurrent activities. It visually
depicts the workflow as well as what causes an event to occur.
 Use Case Diagram: It represents the functionality of a system by utilizing actors and use
cases. It encapsulates the functional requirement of a system and its association with actors.
It portrays the use case view of a system.

3. Interaction Diagrams
Interaction diagrams are a subclass of behavioral diagrams that give emphasis to object interactions
and also depicts the flow between various use case elements of a system. In simple words, it shows
how objects interact with each other and how the data flows within them. It consists of
communication, interaction overview, sequence, and timing diagrams.
 Sequence Diagram: It shows the interactions between the objects in terms of messages
exchanged over time. It delineates in what order and how the object functions are in a
system.
 Communication Diagram: It shows the interchange of sequence messages between the
objects. It focuses on objects and their relations. It describes the static and dynamic behavior
of a system.
 Timing Diagram: It is a special kind of sequence diagram used to depict the object's
behavior over a specific period of time. It governs the change in state and object behavior by
showing the time and duration constraints.
 Interaction Overview diagram: It is a mixture of activity and sequence diagram that
depicts a sequence of actions to simplify the complex interactions into simple interactions.

Principles of Object-Oriented Systems


The conceptual framework of object–oriented systems is based upon the object model. There are
two categories of elements in an object-oriented system −
Major Elements − By major, it is meant that if a model does not have any one of these elements, it
ceases to be object oriented. The four major elements are −
 Abstraction
 Encapsulation
 Modularity
 Hierarchy
Minor Elements − By minor, it is meant that these elements are useful, but not indispensable part
of the object model. The three minor elements are −
 Typing
 Concurrency
 Persistence

Abstraction
Abstraction means to focus on the essential features of an element or object in OOP, ignoring its
extraneous or accidental properties. The essential features are relative to the context in which the
object is being used.
Grady Booch has defined abstraction as follows −
“An abstraction denotes the essential characteristics of an object that distinguish it from all other
kinds of objects and thus provide crisply defined conceptual boundaries, relative to the perspective
of the viewer.”
Example − When a class Student is designed, the attributes enrolment_number, name, course, and
address are included while characteristics like pulse_rate and size_of_shoe are eliminated, since
they are irrelevant in the perspective of the educational institution.

Encapsulation
Encapsulation is the process of binding both attributes and methods together within a class.
Through encapsulation, the internal details of a class can be hidden from outside. The class has
methods that provide user interfaces by which the services provided by the class may be used.

Modularity
Modularity is the process of decomposing a problem (program) into a set of modules so as to reduce
the overall complexity of the problem. Booch has defined modularity as −
“Modularity is the property of a system that has been decomposed into a set of cohesive and loosely
coupled modules.”
Modularity is intrinsically linked with encapsulation. Modularity can be visualized as a way of
mapping encapsulated abstractions into real, physical modules having high cohesion within the
modules and their inter–module interaction or coupling is low.

Hierarchy
In Grady Booch’s words, “Hierarchy is the ranking or ordering of abstraction”. Through hierarchy, a
system can be made up of interrelated subsystems, which can have their own subsystems and so on
until the smallest level components are reached. It uses the principle of “divide and conquer”.
Hierarchy allows code reusability.
The two types of hierarchies in OOA are −
 “IS–A” hierarchy − It defines the hierarchical relationship in inheritance, whereby from a
super-class, a number of subclasses may be derived which may again have subclasses and so
on. For example, if we derive a class Rose from a class Flower, we can say that a rose “is–a”
flower.
 “PART–OF” hierarchy − It defines the hierarchical relationship in aggregation by which a
class may be composed of other classes. For example, a flower is composed of sepals,
petals, stamens, and carpel. It can be said that a petal is a “part–of” flower.

Typing
According to the theories of abstract data type, a type is a characterization of a set of elements. In
OOP, a class is visualized as a type having properties distinct from any other types. Typing is the
enforcement of the notion that an object is an instance of a single class or type. It also enforces that
objects of different types may not be generally interchanged; and can be interchanged only in a very
restricted manner if absolutely required to do so.
The two types of typing are −
 Strong Typing − Here, the operation on an object is checked at the time of compilation, as
in the programming language Eiffel.
 Weak Typing − Here, messages may be sent to any class. The operation is checked only at
the time of execution, as in the programming language Smalltalk.

Concurrency
Concurrency in operating systems allows performing multiple tasks or processes simultaneously.
When a single process exists in a system, it is said that there is a single thread of control. However,
most systems have multiple threads, some active, some waiting for CPU, some suspended, and
some terminated. Systems with multiple CPUs inherently permit concurrent threads of control; but
systems running on a single CPU use appropriate algorithms to give equitable CPU time to the
threads so as to enable concurrency.
In an object-oriented environment, there are active and inactive objects. The active objects have
independent threads of control that can execute concurrently with threads of other objects. The
active objects synchronize with one another as well as with purely sequential objects.

Persistence
An object occupies a memory space and exists for a particular period of time. In traditional
programming, the lifespan of an object was typically the lifespan of the execution of the program
that created it. In files or databases, the object lifespan is longer than the duration of the process
creating the object. This property by which an object continues to exist even after its creator ceases
to exist is known as persistence.
Inheritance Definition
We live in a world where we find software and programming everywhere. The modern-day
programming languages are strongly built on the Object-Oriented Programming (shortly
abbreviated as OOPs) concept. OOP is a paradigm that helps programmers structure their code so
that they are easy to maintain, understand, and override. The four pillars of the OOP paradigm
are Abstraction, Encapsulation, Inheritance and Polymorphism. Now, instead of me bragging
more about OOPs, let us start with Inheritance. Because that's what this tutorial is all about.

What is Inheritance?
The term 'Inheritance' is derived from the word "Inherit" which means, "to derive any quality,
features or characteristics from family". Therefore, "Inheritance is defined as a mechanism where
the sub or child class inherits the properties and characteristics of the super class or other derived
classes. It also supports additional features of extracting properties from the child class and using it
into other derived classes."
In computer programming, Inheritance is one of the most important concepts followed by
Abstraction, Encapsulation and Polymorphism in the Object Oriented Programming (OOPS)
Paradigm. This mechanism allows the new objects to take on the properties of existing objects.
Inheritance builds relationships within the classes; therefore, relating two or more classes to each
other and establishing class hierarchies. Rather than writing the same code, again and again, the
programmers can use the code that is already created by inheriting its class.

Understanding Inheritance
To dig deep more into inheritance, firstly we need to understand the two types of programming
classes
1. Sub Class
2. Super Class
An inherited class is known as Sub Class or Derived Class. Sub Class inherits the properties or
characteristics from Base Class, also popularly known as Super class.
In the programming world, Sub Class is also referred to as a child class, whereas the superclass is
referred to as parent class.

How Does Inheritance Make Programming Easy?


In object-oriented programming, a programmer creates a class and defines objects, data members
and data functions in that class. Data members are a reference to objects (of any type), or the
variables declared in a class where Data functions are defined as methods or functions designated in
the class. Coders use these functions to manipulate the data members. These data members and
member functions can be declared using the keyword public or private, depending upon the scope
of use.
With the OOPs Inheritance mechanism, programmers need not recursively create the data members
and data functions in the same code. They create and define the data member and function once
in the superclass, and they make the derived class inherit all attributes and properties of data
members and functions of its superclass. Therefore supports effective dynamic programming
making work easier.

Types of Inheritance
1. Single Inheritance:

In this type, the child class inherits the properties from the superclass.
In the below example, you will notice class One is the superclass, and class Two is the base class.
Therefore, class Two inherits the properties and behaviour of the base class One.
Syntax
1. //Super Class   
2. class One    
3. {    
4. public void addOne()    
5. {    
6. //CODE TO DO:    
7. }   
8. }    
9. //Child Class   
10. class Two : One   
11. {    
12. public void addTwo()    
13. {    
14. //CODE TO DO:    
15. }   
16. }  
2. Multiple Inheritance:

The child class inherits the properties and features from two or more parent classes with this type.
In the below example, you will notice class Three inherits the features and behaviour of class Two.
Further, class Two inherits the properties of class One. Therefore, we can conclude that class One is
the base class of class Two, whereas class Two is the base class of class Three.
Hence, class Three implicitly inherits the behaviour and properties of class One along with class
Two, thereby creating a multiple inheritance.
Syntax
1. //Superclass   
2. class One    
3. {    
4. public void addOne()    
5. {    
6. //CODE TO DO:    
7. }   
8. }    
9. //child Class   
10. class Two : One   
11. {    
12. public void addTwo()    
13. {    
14. //CODE TO DO:    
15. }   
16. }    
17. //Derived Class   
18. class Three : Two   
19. {    
20. //CODE TO DO:      
21. {    
22. //TO DO:    
23. }   
24. }  
3. Multilevel Inheritance:

With this type, one child class inherits the properties and behavior from two or more superclasses.
In the below example, class three inherits the properties, functions and objects for both class Two
and class One at the same level. Therefore, both class One and class Two are the superclasses for
class Three.
Syntax
1. //Super Class   
2. class One   
3. {    
4. public void addOne()    
5. {    
6. //CODE TO DO:    
7. }   
8. }    
9. //Super Class   
10. class Two   
11. {    
12. public void addTwo()    
13. {    
14. //CODE TO DO:    
15. }   
16. }    
17. //Child Class   
18. class Three : One, Two   
19. {    
20. public void addThree()    
21. {    
22. //CODE TO DO:    
23. }   
24. }  
4. Hierarchal Inheritance:

In the Hierarchical Inheritance type, two or more child classes inherit the properties and behaviors
from one superclass.
In the below example, the following hierarchies:
(I) The base class One has two derived classes, i.e., class Two and class Three.
(II) Next, class Two acts as a base class for two child classes named Six and Seven.
(III) Further, class three is also a base class for class Four and class Five, respectively.
Syntax
1. //Superclass   
2. class One   
3. {    
4. public void addOne()    
5. {    
6. //CODE TO DO:    
7. }   
8. }    
9. //Child Class   
10. class Two : One   
11. {    
12. public void addTwo()    
13. {    
14. //CODE TO DO:    
15. }   
16. }    
17. //Child Class   
18. class Three : One   
19. {    
20. public void addThree()    
21. {    
22. //CODE TO DO:    
23. }   
24. }    
25. //Child Class   
26. class Four : Three   
27. {    
28. public void addFour()    
29. {    
30. //CODE TO DO:    
31. }   
32. }    
33. //Child Class   
34. class Five : Three   
35. {    
36. public void addFive()    
37. {    
38. //CODE TO DO:    
39. }   
40. }    
41. //child Class   
42. class Six : Two   
43. {    
44. public void addSix()    
45. {    
46. //CODE TO DO:    
47. }   
48. }    
49. //Child Class   
50. class Seven :Two   
51. {    
52. public void addSeven()    
53. {    
54. //CODE TO DO:    
55. }   
56. }   
5. Hybrid Inheritance:

With this type, the programmer can call a combination of two or more types of inheritance.
Therefore the code can include a combination of Multiple and Hierarchical inheritance, Multilevel
and Hierarchical inheritance or Hierarchical and Multipath inheritance, or it may be a combination
of three of them, i.e., Multiple, Multilevel and Multiple Hierarchical inheritance.
Syntax
1. //Superclass   
2. class One   
3. {    
4. public void addOne()    
5. {  //CODE TO DO:    
6. }   
7. }    
8. //Super Class   
9. class Six   
10. {    
11. public void addSix()    
12. {    
13. //CODE TO DO:    
14. }   
15. }    
16. //Child Class   
17. class Two : One, Six   
18. {    
19. public void addTwo()    
20. {    
21. //CODE TO DO:  
22. }   
23. }    
24. //Child Class   
25. class Three : One   
26. {    
27. public void addThree()    
28. {    
29. //CODE TO DO:  
30. }   
31. }    
32. //Child Class   
33. class Four : Three   
34. {    
35. public void addFour()    
36. {    
37. //CODE TO DO:    
38. }   
39. }    
40. //Child Class   
41. class Five : Three   
42. {    
43. public void addFive()    
44. {    
45. //CODE TO DO:     
46. }  
47. }  

Advantages of Inheritance
Given below are some advantages of Inheritance.
 Recursive code is written once. Therefore, allowing code reusability.
 One base class can be used for one or more derived classes in a hierarchy.
 It saves time, as the programmer does not change the value in all the base classes; they
change it in a parent class, and the base class inherits the change.
 OOPs Inheritance is used to create dominant objects.
 Inheritance prevents data duplicity and redundancy.
 Inheritance reduces space and time complexity.

Redefining Property in UML


UML allows some properties of a generalization of a specializing classifier to be redefined instead
of being inherited. Redefinition could be done to rename, augment, constrain, or override the
redefined members in the context of instances of the specializing classifier.
The concept and notation for the redefinition was introduced in UML 2.0. It was not present in the
older UML 1.x.
Redefining property will replace any reference to a redefined property in the context of an
instance of the specializing classifier. A property could be redefined to have different
 name,
 visibility,
 type,
 default value.
UML requires redefining property "to be consistent" with the property it redefines, while it may add
specific constraints or "other details" that are particular to instances of the specializing classifier and
do not contradict existing constraints. Because name, visibility, and default values could be
completely different, it looks that this "consistency" for properties usually means that the type of
redefining property should be a "kind of type" (e.g. subclass) of redefined property.
One special case of redefinition is when a derived property redefines one which is not derived. The
constraints implied by the derivation should be maintained if the property is updated.
Redefinition may be either explicitly notated with the use of a {redefines <property>} property
string or applied implicitly if redefining property cannot be distinguished from redefined property.
UML 2.0 to 2.1.2 required all redefinitions to be made explicit. This requirement was relaxed in the
latest UML specifications. Still, when in doubt it is easier to use explicit {redefines <property>}
notation to make your intentions clear.
Example below shows Library Book class with redefined attributes title, author, lang, and
loanPeriod. Two of those are explicitly notated as redefined.

Library book has redefined attributes


title, author, lang, and loanPeriod.
The title attribute explicitly redefines name. While type of the attributes is the same, name is
different. The author attribute is redefined implicitly. Name of the attribute is the same while we
assume that Author type is kind of a Person, so that they are "consistent".
The lang attribute is explicitly redefined with different type. Original type was free text String,
while redefined attribute is more specific (e.g. enumerated) Language class. We used explicit
redefinition in this case because attribute types String and Language seem not to be related.
The loanPeriod attribute is an example of a derived property redefining one which is not derived.
The default length of time a Book may be borrowed (loan period) was originally set to 14 (days)
while for the Library Book it was redefined as derived because it is calculated based on a library
policy, and varies based on a kind of a book and who is borrowing it. For example, in a university
library undergraduates could borrow book for 30 days, graduate students for a quarter, and faculty
staff for a year. In a public library normal loan period for a book could be 3 weeks, while it could be
lowered to 2 weeks for new books. UML considers property redefined both when it becomes
derived and if default value is changed.

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


 Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example of method overriding


In this example, we have defined the run method in the subclass as defined in the parent class but it
has some specific implementation. The name and parameter of the method are the same, and there is
IS-A relationship between the classes, so there is method overriding.
1. //Java Program to illustrate the use of Java Method Overriding  
2. //Creating a parent class.  
3. class Vehicle{  
4.   //defining a method  
5.   void run(){System.out.println("Vehicle is running");}  
6. }  
7. //Creating a child class  
8. class Bike2 extends Vehicle{  
9.   //defining the same method as in the parent class  
10.   void run(){System.out.println("Bike is running safely");}  
11.     public static void main(String args[]){  
12.   Bike2 obj = new Bike2();//creating object  
13.   obj.run();//calling method  
14.   }  
15. }  
Output:
Bike is running safely
There is also the case where you have to change the datatypes on the fly to keep
up with the dynamics of the program. Let us look at how we do that.

Type Conversion in Java


Yes, you guessed it right. Type Conversion is indeed the conversion of variables
from one data type to another. In Java, there are two main types of type conver-
sion.

1. Explicit Type Conversion


2. Implicit Type Conversion
Before we understand that we have to know the size hierarchy of data types.
Let us observe all of them in increasing order in the list below.

 byte
 short
 int
 long
 float
 double
Implicit Type Conversion
Java converts shorter data types to larger data types when they are assigned to
the larger variable.

For example, if you assign a short value to an int variable then Java does the
work for you and converts the short value to an int and stores it in the int vari-
able.

This is similar to the fact that you can put a raisin in a XXL polythene bag. How-
ever, if you want to put the inverse you have to work out a solution because it is
not going to be easy.

Let us look at examples now!

Java program to illustrate automatic type conversion.


package com.dataflair.typeconversion;
public class ImplicitConversion
{
public static void main(String[] args) {
int numberint;
short numbershort;
byte numberbyte;
float numberfloat;
double numberdouble;
long numberlong;
//We have the datatypes we need. Now let us set a value to the shortest datatype.
//That is byte.
numberbyte=21;
numbershort=numberbyte;
numberint=numbershort;
numberlong=numberint;
numberfloat=numberlong;
numberdouble=numberfloat;
System.out.println("The short value is "+numbershort);
System.out.println("The byte value is "+numberbyte);
System.out.println("The int value is "+numberint);
System.out.println("The long value is "+numberlong);
System.out.println("The float value is "+numberfloat);
System.out.println("The long value is "+numberdouble);
System.out.println("This is explicit conversion");
}
}
Output:
The short value is 21
The byte value is 21
The int value is 21
The long value is 21
The float value is 21.0
The long value is 21.0
This is explicit conversion
Observe how the value in short automatically got converted to int without any
explicit action by the programmer. This is automatic conversion. Java does this
when you assign a lower size variable to a higher larger variable.

If you are having trouble learning about the different types of datatypes please
read the “Datatypes in Java” article first.

Okay back to where we were. Now if you go ahead and try a different way of con-
verting the data types, the compiler would not be happy. Don’t believe me? Let
us try it out then.

Java program to discuss the problem with type conversion:


package com.dataflair.typeconversion;
public class ExplicitProblem {
public static void main(String[] args) {
int a=57;
byte b =a;
System.out.print(b);
}
}
Output:
ExplicitProblem.java:5: error: incompatible types: possible lossy conversion
from int to byte
byte b =a;
^

Explicit Type Conversion in Java


The conversion is lossy because the variable int is larger in size than the data
type byte. That is why the compiler thinks it’s not safe to convert the entire data
type because it would lose data.

Do not worry just yet, there is a beautiful work around for this problem and we
are going to see that now.

Java program to illustrate the working of explicit conversion in Java

Whenever you want to explicitly convert the value of a certain data type to one
lesser in size then you must use the name of the data type bound by round brack-
ets in front of the variable name.

package com.dataflair.
public class ExplicitProblem {
public static void main(String[] args) {
int a=257;
byte b =(byte)a;
System.out.print(b);
}
}
Output:
1

Java protected keyword


A Java protected keyword is an access modifier. It can be assigned to variables, methods,
constructors and inner classes.

Points to remember
o The protected access modifier is accessible within the package. However, it can also
accessible outside the package but through inheritance only.

o We can't assign protected to outer class and interface.

o If you make any constructor protected, you cannot create the instance of that class
from outside the package.
o If you are overriding any method, overridden method (i.e., declared in the subclass)
must not be more restrictive.

o According to the previous point, if you assign protected to any method or variable,
that method or variable can be overridden to sub-class using public or protected
access modifier only

Examples of protected keyword


Example 1
Let's see an example to determine whether the protected variable is accessible or not out -
side the package.
1. //save by A.java  
2. package com.java;  
3.   
4. public class A {  
5.   
6.  protected String msg="Try to access the protected variable outside the package";  
7.        
8. }  
9. //save by ProtectedExample1.java  
10. package com.javatpoint;  
11. import com.java.A;  
12.   
13. public class ProtectedExample1 {  
14. public static void main(String[] args) {  
15.     A a=new A();  
16.    System.out.println(a.msg);  
17.       
18. }  
19. }  
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The field A.msg is not visible

Example 2
Let's see an example to determine whether the protected variable is accessible or not out -
side the class and within the package.
1. class A {  
2.   
3.  protected String msg="Try to access the protected variable outside the class within 
the package";  
4.        
5. }  
6. public class ProtectedExample2 {  
7. public static void main(String[] args) {  
8.     A a=new A();  
9.    System.out.println(a.msg);  
10. }  
11. }  
Output:
Try to access the protected variable outside the class within the package

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

1. variable

2. method

3. class

The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the construc-
tor only. The blank final variable can be static also which will be initialized in the static
block only. We will have detailed learning of these. Let's first learn the basics of final key-
word.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.
1. class Bike9{  
2.  final int speedlimit=90;//final variable  
3.  void run(){  
4.   speedlimit=400;  
5.  }  
6.  public static void main(String args[]){  
7.  Bike9 obj=new  Bike9();  
8.  obj.run();  
9.  }  
10. }//end of class  
Test it Now
Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

Example of final method


1. class Bike{  
2.   final void run(){System.out.println("running");}  
3. }  
4.      
5. class Honda extends Bike{  
6.    void run(){System.out.println("running safely with 100kmph");}  
7.      
8.    public static void main(String args[]){  
9.    Honda honda= new Honda();  
10.    honda.run();  
11.    }  
12. }  
Test it Now
Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.

Example of final class


1. final class Bike{}  
2.   
3. class Honda1 extends Bike{  
4.   void run(){System.out.println("running safely with 100kmph");}  
5.     
6.   public static void main(String args[]){  
7.   Honda1 honda= new Honda1();  
8.   honda.run();  
9.   }  
10. }  
Test it Now
Output:Compile Time Error

Q) Is final method inherited?


Ans) Yes, final method is inherited but you cannot override it. For Example:
1. class Bike{  
2.   final void run(){System.out.println("running...");}  
3. }  
4. class Honda2 extends Bike{  
5.    public static void main(String args[]){  
6.     new Honda2().run();  
7.    }  
8. }  
Test it Now
Output:running...

Q) What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final vari-
able.

If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an em-
ployee.

It can be initialized only in constructor.

Example of blank final variable


1. class Student{  
2. int id;  
3. String name;  
4. final String PAN_CARD_NUMBER;  
5. ...  
6. }  
Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:


1. class Bike10{  
2.   final int speedlimit;//blank final variable  
3.     
4.   Bike10(){  
5.   speedlimit=70;  
6.   System.out.println(speedlimit);  
7.   }  
8.   
9.   public static void main(String args[]){  
10.     new Bike10();  
11.  }  
12. }  
Test it Now
Output: 70

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static
blank final variable. It can be initialized only in static block.

Example of static blank final variable


1. class A{  
2.   static final int data;//static blank final variable  
3.   static{ data=50;}  
4.   public static void main(String args[]){  
5.     System.out.println(A.data);  
6.  }  
7. }  

Q) What is final parameter?

If you declare any parameter as final, you cannot change the value of it.
1. class Bike11{  
2.   int cube(final int n){  
3.    n=n+2;//can't be changed as n is final  
4.    n*n*n;  
5.   }  
6.   public static void main(String args[]){  
7.     Bike11 b=new Bike11();  
8.     b.cube(5);  
9.  }  
10. }  
Test it Now
Output: Compile Time Error

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only function-
ality to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)

2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.

Points to Remember

o An abstract class must be declared with an abstract keyword.

o It can have abstract and non-abstract methods.

o It cannot be instantiated.

o It can have constructors and static methods also.


o It can have final methods which will force the subclass not to change the body of
the method.

Example of abstract class


1. abstract class A{}  

Abstract Method in Java


A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method


1. abstract void printStatus();//no method body and abstract  

Example of Abstract class that has an abstract method


In this example, Bike is an abstract class that contains only one abstract method run. Its im-
plementation is provided by the Honda class.
1. abstract class Bike{  
2.   abstract void run();  
3. }  
4. class Honda4 extends Bike{  
5. void run(){System.out.println("running safely");}  
6. public static void main(String args[]){  
7.  Bike obj = new Honda4();  
8.  obj.run();  
9. }  
10. }  
Test it Now
running safely

Understanding the real scenario of Abstract class


In this example, Shape is the abstract class, and its implementation is provided by the Rec -
tangle and Circle classes.

Mostly, we don't know about the implementation class (which is hidden to the end user),
and an object of the implementation class is provided by the factory method.

A factory method is a method that returns the instance of the class. We will learn about
the factory method later.
In this example, if you create the instance of Rectangle class, draw() method of Rectangle
class will be invoked.

File: TestAbstraction1.java

1. abstract class Shape{  
2. abstract void draw();  
3. }  
4. //In real scenario, implementation is provided by others i.e. unknown by end user  
5. class Rectangle extends Shape{  
6. void draw(){System.out.println("drawing rectangle");}  
7. }  
8. class Circle1 extends Shape{  
9. void draw(){System.out.println("drawing circle");}  
10. }  
11. //In real scenario, method is called by programmer or user  
12. class TestAbstraction1{  
13. public static void main(String args[]){  
14. Shape s=new Circle1();//In a real scenario, object is provided through method, e.g., 
getShape() method  
15. s.draw();  
16. }  
17. }  
Test it Now
drawing circle

Another example of Abstract class in java


File: TestBank.java

1. abstract class Bank{    
2. abstract int getRateOfInterest();    
3. }    
4. class SBI extends Bank{    
5. int getRateOfInterest(){return 7;}    
6. }    
7. class PNB extends Bank{    
8. int getRateOfInterest(){return 8;}    
9. }    
10.     
11. class TestBank{    
12. public static void main(String args[]){    
13. Bank b;  
14. b=new SBI();  
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
16. b=new PNB();  
17. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");    
18. }}    
Test it Now
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Abstract class having constructor, data member and


methods
An abstract class can have a data member, abstract method, method body (non-abstract
method), constructor, and even main() method.

File: TestAbstraction2.java

1. //Example of an abstract class that has abstract and non-abstract methods  
2.  abstract class Bike{  
3.    Bike(){System.out.println("bike is created");}  
4.    abstract void run();  
5.    void changeGear(){System.out.println("gear changed");}  
6.  }  
7. //Creating a Child class which inherits Abstract class  
8.  class Honda extends Bike{  
9.  void run(){System.out.println("running safely..");}  
10.  }  
11. //Creating a Test class which calls abstract and non-abstract methods  
12.  class TestAbstraction2{  
13.  public static void main(String args[]){  
14.   Bike obj = new Honda();  
15.   obj.run();  
16.   obj.changeGear();  
17.  }  
18. }  
Test it Now
bike is created
running safely..
gear changed

You might also like