Unit 2 Java
Unit 2 Java
9/7/2021 1
Object Oriented Analysis and Design using Java
Introduction to OO Programming
Constructor
• A constructor initializes an object when it is created.
• It has the same name as its class and is syntactically similar to a method.
• Typically, you will use a constructor to give initial values to the instance variables defined by the class,
or to perform any other start-up procedures required to create a fully formed object.
• All classes have constructors, whether you define one or not, because Java automatically provides a
default constructor that initializes all member variables to zero or corresponding default value.
However, once you define your own constructor, the default constructor is no longer added.
• Each time a object is created using new operator, constructor is invoked to assign initial values to
Class Student
{
Student( )
{
// initialization
}
}
• A constructor that has no parameters. If we don’t define a constructor for a class, then compiler creates a
default constructor.
• Default constructor provides default values to the objects like 0, false, null etc depending on the data type
of the instance variables.
Parameterized constructor:
If the constructor is made private, you cannot create the instance of that class from outside the class.
By default the access modifier is “default”
class A{
private A() { } //private constructor
void msg(){[Link](“Welcome to OOAD with java class");}
}
public class Sample
{
public static void main(String args[]){
A obj=new A(); //Compile Time Error
}
}
Object Oriented Analysis and Design using Java
Object Oriented Programming: Garbage Collector
• Java Garbage Collection is the process to identify and remove the unused
objects from the memory and free space.
• One of the best feature of java programming language is the automatic
garbage collection, unlike other programming languages such as C where
memory allocation and de-allocation is a manual process.
• Garbage Collector is the program running in the background that looks into
all the objects in the memory and find out objects that are not referenced by
any part of the program.
• All these unreferenced objects are deleted and space is reclaimed for
allocation to other objects.
Object Oriented Analysis and Design using Java
Object Oriented Programming: finalization
• Java run time calls this method whenever it is about to recycle an object of the class.
• Keyword protected is used to prevent access to finalize ( ) by the code defined outside the class
hierarchy.
• Called just prior to garbage collection and not called when an object goes out of scope
Parameter Passing –
Value Types and Reference Types
1. Introduction
Introduction
• Argument is copied to the parameter when some data has to be passed between methods /
functions.
• 2 Types of Parameters
○ Formal Parameter
○ Actual Parameter
• Parameter passing techniques
○ Pass by Value
○ Pass by Reference
Object Oriented Analysis and Design with Java
Parameter Passing
f1(val1, val2)
• Changes made to formal parameter do not
get transmitted back to the caller. creates a copy of v1 10 12
f1 works on
and v2
f1(num1, num2) copy of v1 and
• Any modifications to the formal v2
{
parameter variable inside the called x
=40;
y
function or method affect only the =50;
/
separate storage location and will not be / other stmts;
calling environment.
Object Oriented Analysis and Design with Java
Parameter Passing
References- alias
• Non-Primitive types are references.
Call by Reference
• Changes made to formal parameter do get class A
obj
{
transmitted back to the caller through int x; 2008
void f1( A obj)
parameter passing. #4016
{
• Any changes to the formal parameter are obj x = 20;
}
reflected in the actual parameter in the calling }
Overloading of Methods
1. Introduction
2. Coding examples
Object Oriented Analysis and Design with Java
Method Overloading
Introduction
• A feature that allows a class to have more than one method having the same name, if their argument lists are
different.
• Method overloading is also known - Compile Time polymorphism, Static polymorphism , Early Binding.
• Three ways to overload : The argument lists of the methods must differ in either of these:
■ Changing the number of parameters
■ Changing the data type of parameters
■ Changing the order of parameters of methods.
Object Oriented Analysis and Design with Java
Method Overloading
Introduction to OO Programming
Mahitha G Bhargavi M
Department of Computer Science and Engineering
2
Object Oriented Analysis and Design using Java
Method Types
Instance Methods
Instance method are methods which require an object of its class to be created before it can be called. To invoke a
instance method, we have to create an Object of the class in which the method is defined.
Static Methods
Static methods are the methods in Java that can be called without creating an object of class.
They are referenced by the class name itself or reference to the Object of that class.
class example1 {
public static void main(String[] args)
{
[Link]
[Link]
[Link]
Why Java
main
method is
static????
Object Oriented Analysis and Design using Java
Static Method
Object Oriented Analysis and Design using Java
Static Method
class example2 {
public static void main(String[] args)
{
A class can be made static only if it is a nested class. We cannot declare a top-level class
with a static modifier but can declare nested classes as static. Such types of classes are called
Nested static classes. Nested static class doesn’t need a reference of Outer class. In this case,
a static class cannot access non-static members of the Outer class.
THANK YOU
Syntax:
• Multilevel Inheritance
• Hierarchical Inheritance
Object Oriented Analysis and Design with Java
Types of Inheritance -Example
Hierarchical Inheritance
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}
}
Object Oriented Analysis and Design with Java
Access Specifier
• Access specifiers in Java control the visibility and accessibility of classes, methods and variables within
a program.
• They ensure encapsulation and maintain security and integrity of code.
• Programming example : p1 and p2 folders.
package p1;
public class A
{
•
public void display()
{ Public access specifier has the widest scope among
[Link]("Public method");
all other access specifiers.
}
} • Classes, methods, data members that are declared
package p2;
import p1.*; public are accessible from everywhere in the
class B {
program. There is no restriction on the scope of
public static void main(String args[])
{ the data members.
A obj = new A();
[Link]();
}
}
Output - Public method
Object Oriented Analysis and Design with Java
Access Specifier – protected
package p1;
public class A
{
protected void display()
{
[Link]("Protected method");
} • Methods or data members declared as protected
}
package p2;
are accessible within the same package or
import p1.*; // importing all classes in package p1
subclasses in different packages.
class B extends A // Class B is subclass of A
{ • Facilitates inheritance and code organization.
public static void main(String args[])
{
B obj = new B();
[Link]();
}
}
Output - Protected method
Object Oriented Analysis and Design with Java
Method Over-riding
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.
● 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
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).
Object Oriented Analysis and Design with Java
Method Over-riding
Program [Link]
Object Oriented Analysis and Design with Java
Super keyword in java
Programming example
[Link]
[Link]
[Link]
THANK YOU
Mahitha G & Bhargavi M
Department of Computer Science and Engineering
mahithag@[Link]
Object Oriented Analysis and Design
using Java - UE21CS352
Implementation of
• Same Base Class Garbage Collector is
In Java all objects have
became easy since
Asobjects
common
All Java was in created
interface
Java to are
• Common Interface required
from scratch,
implement
inherited andit ithas
from sameno
implementation is
• It enables easy memory backward
makes compatibility
baseimplementation
class called
provided in the base
management issues with
of Garbage any existing
collector
'Object'. lot
class, enabling to send
language
easier in Java.
• Simplifies argument passing amongst messages to every
object too on the heap. object.
The singly-rooted hierarchy is common with most other
object-oriented programming languages.
Object Oriented Analysis and Design using Java
Object class -Introduction
• Object class defined by Java is a super class of all other classes, in the absence of any other explicit
superclass
• Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects,
including arrays, implement the methods of this class
• A reference variable of type Object can refer to an object of any class
• This is defined in the [Link] package
Object Oriented Analysis and Design using Java
Object class Methods
● Whenever it is invoked on the same object more than once during an execution of a Java application, the
hashCode method must consistently return the same integer. This integer need not remain consistent from one
execution of an application to another execution of the same application.
Object Oriented Analysis and Design using Java
Object class Methods
Interfaces
You would have heard of the story of the fox and the stork – each one hosting a
feast to the other. The fox serves the soup on a flat plate. The stork serves the
soup in a pitcher with a narrow deep opening. The stork does not get the right
interface to enjoy its meal when fox serves it. The fox does not get the right
interface when the stork serves it. The moral of the story - interface matters the
So next
most. topic is
interfaces
in java
Object Oriented Analysis and Design with Java
Interface in Java
Syllabus of OOPJ is an interface. The teachers implement this interface. You are the clients. But
unfortunately, in this case, you can not chose the implementation! The students of A & G section
are tied to my implementation! In our department, we have already experimented with students
choosing the implementation – choose which teacher (elective)! A day may come when you can
choose a different teacher for each topic!
An interface in Java specifies the method signatures and has no default implementation. So,
these methods are abstract and also public
public interface Displayable
{
void disp();
}
Object Oriented Analysis and Design with Java
Interface in Java
• We know, objects define their interaction with the outside world through the
methods that they expose.
• Buttons on the front of your television set, for example, are the interface between
you and the electrical wiring on the other side of its plastic casing.
• You press the "power" button to turn the television on and off.
In its most common form, an interface is a group of related methods with empty
bodies.
Object Oriented Analysis and Design with Java
Interface
Interface i1
{
Void display();
}
Interface i2 extends i1
{
Void print();
}
NO. you cannot have a constructor. There is no default constructor. You can not make one either.
We can. But these will for the whole class and will be immutable. In Java terminology, these will be
static and final. So, the client of the class has a guarantee about these members. They exist in
every class implementing the interface, can be accessed through the class or the object – no
difference though – will never change
• Can a class with all methods implemented also be abstract?
It can be. If creating an object of that class does not make sense in the domain of application, the
class can be made abstract.
Object Oriented Analysis and Design with Java
Interface in Java
[Link]
[Link]
[Link]
interfacedemo_new.java
THANK YOU
Mahitha G and Bhargavi M
Department of Computer Science and Engineering
mahithag@[Link]
Object Oriented Analysis and Design
using Java - UE21CS352B
Abstract Class
Introduction
• 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:
• If a class includes abstract methods, then the class itself must be declared abstract
public abstract class GraphicObject {
// declare fields
// declare non abstract 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.
Object Oriented Analysis and Design using Java
Abstract class
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.
Object Oriented Analysis and Design using Java
Abstract class
Coding Example: If the abstract class contains the below data, how to implement Rectangle
and Triangle classes? ([Link])
● Reduces programming effort by providing data structures and algorithms so you don't have to write them yourself.
● Increases performance by providing high-performance implementations of data structures and algorithms. Because
the various implementations of each interface are interchangeable, programs can be tuned by switching
implementations.
● Provides interoperability between unrelated APIs by establishing a common language to pass collections back and
forth.
● Reduces the effort required to learn APIs by requiring you to learn multiple ad hoc collection APIs.
● Fosters software reuse by providing a standard interface for collections and algorithms with which to manipulate
them.
Object Oriented Analysis and Design using Java
Collections - Introduction
Object Oriented Analysis and Design using Java
Collections - Introduction
Java Collection means a single unit of objects. Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList, Vector,
LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
add
addall
remove
removeif
size
clear
retainall
Object Oriented Analysis and Design using Java
List Interface
Interfaces List , Queue and Set are inherited from Collection class
List interface
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
● It contains the index-based methods to insert, update, delete and search the elements. It can have the
duplicate elements also. We can also store the null elements in the list.
● List interface is found in the [Link] package and inherits the Collection interface.
● The implementation classes of List interface are ArrayList, LinkedList, Stack and Vector.
Few Methods :
● size(), clear(), add(), Add(),addAll(), contains(), containsAll(), equals(), hashCode(), isEmpty(), indexOf().
etc…
Object Oriented Analysis and Design using Java
Introduction to ArrayList Class in Java
Declaration :
Few Methods()
● Java Collection framework provides a Stack class that models and implements a Stack data
structure.
● The class is based on the basic principle of last-in-first-out [LIFO].
Declaration:
public class Stack<E> extends Vector<E>
Implemented interfaces :
● Serializable: It is a marker interface that classes must implement if they are to be serialized and
deserialized.
● Cloneable: This is an interface in Java which needs to be implemented by a class to allow its objects to
be cloned.
● Iterable<E>: This interface represents a collection of objects which is iterable — meaning which can be
iterated.
● Collection<E>: A Collection represents a group of objects known as its elements. The Collection
interface is used to pass around collections of objects where maximum generality is desired.
● List<E>: The List interface provides a way to store the ordered collection. It is a child interface of
Collection.
● RandomAccess: This is a marker interface used by List implementations to indicate that they support
fast (generally constant time) random access.
Object Oriented Analysis and Design using Java
Introduction to Stack Class in Java
● Few Methods:
○ empty()
○ push(E item).
○ pop()
○ peek()
○ search(Object o)
Object Oriented Analysis and Design using Java
Programming Examples
● Programming Example:
[Link]
[Link]
[Link]
THANK YOU
• System design: The development teams devise a high – level strategy called the system
architecture for solving the application problem.
• Class design : The class designer adds details to the analysis model in accordance with the system
design strategy. The focus of class design is the data structures and algorithms needed to
implement each class.
• Implementation : Implementers translate the classes and relationships developed during class
design into particular programming language, database or hardware. During implementation, it is
important to follow good software engineering practice so that traceability to the design is
apparent and so that the system remains flexible and extensible.
Object Oriented Analysis and Design with Java
Sample
Object Oriented Analysis and Design with Java
System Design
• The first design stage for devising the basic approach to solve the problem.
• Developers make decisions about how the problem will be solved, first at a high
level and then with more details – Overall structure and style.
• Need to apply high level strategy – System Architecture – for solving the problem
and building a solution. It determines the organization of the system into
subsystems. Also provides the context for the detailed decisions that are made in
later stages.
Object Oriented Analysis and Design with Java
Decisions - System Design
1. Estimating performance
2. Making a Reuse plan
3. Breaking system into sub-systems
4. Identifying Concurrency
5. Allocation of Sub Systems to hardware
6. Manage data storage
7. Handling global resources
8. Choosing a software control strategy
9. Handling boundary conditions
10. Set trade-off priorities
• Two different aspects of reuse - Using existing things and Creating reusable things.
• Most developers reuse existing things and a small fraction of developers create new things.
Library Vs Framework
Object Oriented Analysis and Design with Java
Frameworks in detail
• Pre-written code used by Java developers to develop Java applications or web applications.
• A set of cooperating classes that make up a reusable design for a specific class of software.
• It acts like a skeleton that helps the developer to develop an application by writing their
own - The framework is in control of the programmer.
• Provides architectural guidance by partitioning the design into abstract classes.
• A developer will normally customize a framework to a specific application by “subclassing”
and composing instances of framework classes.
• In libraries – you call the library functions. However, in frameworks – the framework
handles the flow of control and calls your code whenever required.
Object Oriented Analysis and Design with Java
Frameworks in Java
• Collections: Provides many interfaces (Set, List, Queue, Deque) and classes
.
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
• Swing: The part of JFC (Java Foundation Classes) built on the top of AWT and
written entirely in Java. The [Link] API provides all the component classes
like JButton, JTextField, JCheckbox, JMenu, etc.
• AWT: An abstract window toolkit that provides various component classes like
Label, Button, TextField, etc., to show window components on the screen. All
these classes are part of the [Link] package.
• Spring, Hibernate, Grails, Play, JavaServer Faces (JSF), Google Web Toolkit
(GWT), Quarkus
Object Oriented Analysis and Design with Java
Framework Example
• Object - Oriented Modeling and Design With UML by RUMBAUGH and BLAHA,
Chapter 1 and 14
• Applying UML and Patterns by Craig Larman, Chapter-34
• [Link]
• What is Object-Oriented Modeling (OOM)? - Definition from Techopedia
• Object oriented methodology ([Link])
• 10 of the Most Popular Java Frameworks of 2020 ([Link])
THANK YOU
Mahitha G & Bhargavi M
Department of Computer Science and Engineering
Object Oriented Analysis and Design
with Java
UE20CS352
Prof. Mahitha G & Bhargavi M
Department of Computer Science and Engineering
UE20CS352: Object Oriented Analysis and Design with Java
Architectural Patterns
• MVC Architecture
• Advantages of MVC
• MVC in Java
• Implementation
Object Oriented Analysis and Design using Java
Introduction to Architectural patterns
• An architectural pattern is a general, reusable solution to a commonly occurring problem in
software architecture
• Some architecture patterns naturally lend themselves toward highly scalable applications,
whereas other architecture patterns naturally lend themselves toward applications that are
highly agile.
• Knowing the characteristics, strengths, and weaknesses of each architecture pattern is necessary
in order to choose the one that meets the specific business needs and goals.
• Layered, event driven, microkernel, microservices, space based and MVC, etc.
Object Oriented Analysis and Design using Java
Model View Controller
• MVC - An architectural pattern in Software Engineering.
• First introduced by Trygve Reenskaug, a Smalltalk developer at the Xerox Palo Alto Research Center in 1979 and
helps to decouple data access and business logic from the manner in which it is displayed to the user.
• A way of designing and building applications that separates application logic from presentation
• Division of application into three main logical components: model, view, and controller.
• A design pattern for computer software considered to distinguish between the data model, processing control and
the user interface.
• It neatly separates the graphical interface displayed to the user from the code that manages the user actions.
• Whenever the controller receives a request from the user (either directly or via the view), it
puts the model to work. And when the model delivers the data requested in the right
format, the controller forwards it to the view
Object Oriented Analysis and Design using Java
Model View Controller architecture
• Well-known design pattern in the web development field. It is a way to organize the code.
• Consists of Data model, presentation information and control information.
• Model: The model represents data and the rules that govern access to and updates of this data. In
enterprise software, a model often serves as a software approximation of a real-world process.
• View: Renders the contents of a model. It specifies exactly how the model data should be presented. If the
model data changes, the view must update its presentation as needed. This can be achieved by using
a push model, in which the view registers itself with the model for change notifications, or a pull model, in
which the view is responsible for calling the model when it needs to retrieve the most current data.
Represents the presentation layer of application. It is used to visualize the data that the model contains.
• Controller: The controller translates the user's interactions with the view into actions that the model will
perform. In a stand-alone GUI client, user interactions could be button clicks or menu selections, whereas
in an enterprise web application, they appear as GET and POST HTTP requests. Depending on the context,
a controller may also select a new view -- for example, a web page of results -- to present back to the user
• The MVC pattern needs all these components to be separated as different objects.
Object Oriented Analysis and Design using Java
Modifying the MVC Design