7/28/2019 Program Paradigm unit i
1/20
UNIT - I
Programming Paradigm-
A programming paradigm is a fundamental style ofcomputer programming
Review OOP
Definition ofoop
Object-Oriented Programming is a technique for programming that focuses on the
data (objects) and on the interfaces to that object
An object-oriented program is made of objects. Each object has a specific
functionality that is exposed to its users, and a hidden implementation.
Software developed using object-oriented techniques are more reliable, easier to
maintain, easier to reuse and enhance and so on. The object- oriented paradigm is effective in
solving many of the outstanding problems in software engineering.
Concepts of OOP
Most important concepts
Encapsulation
It is a mechanism that the code and the data it Manipulates into a single unit and keep
them safe from the external interfaces and misuse.
Data Abstraction
The technique of creating new data types that are well suited to an application to be
programmed is known as data abstraction
Inheritance
Inheritance allows the creation of new class (derived class) from the existing
ones (base class).
Polymorphism
It allows a single name/operator to be associated with different operations
depending on the type of data passed to it.
Other concepts of oops
Message passing
Extensibility
Persistence
Delegation
http://en.wikipedia.org/wiki/Paradigmhttp://en.wikipedia.org/wiki/Computer_programminghttp://en.wikipedia.org/wiki/Paradigmhttp://en.wikipedia.org/wiki/Computer_programming7/28/2019 Program Paradigm unit i
2/20
What is java
Java is universal programming language for all platforms (i.e) platform independent
since it converts every think into byte code.
Why Java and not c++?
The C++ programming language isfar more complex than the Java language. Due to this, C+
+ coding is more error prone than Java code. This has impacts on maintainability1 and
feasibility oflarge project
Garbage collection
No destructor code needed
No cross-compilation needed
Advantages of java
Protable Secure
Simple
Network savy
Java Virtual Machine
Sample Java Code:public class HelloWorld {
// method main(): ALWAYS the APPLICATION entry pointpublic static void main (String[] args) {
System.out.println ("Hello World!");}
}
Object and classes
Objects:
Initially, different parts (entities) of a problem are examined independently. These
entities are chosen because they have some physical or conceptual boundaries that
separate then from the rest of the problem. The entities are then represented as object in
the program.
Java Program Java Complier Virtual Machine
Process of Compilation
Source Code Byte Code
http://www.lrdev.com/lr/java/javacppdiffs.html#note1http://www.lrdev.com/lr/java/javacppdiffs.html#note17/28/2019 Program Paradigm unit i
3/20
An object can be a person, a place, or a thing with which the computer must deal.
Some objects may correspond to real-world entities such as students, employees, bank
accounts, inventory items etc., whereas other may corresponds to computer hardware and
software components a keyboard, mouse, video display, stacks, queues, trees etc., objects
mainly serves the following purpose
To understand the real world and a practical base for designers
Decomposition of a problem into objects depends on judgments and nature
of the problem.
To work with OOP, you should be able to identify three key characteristics of objects:
The objects behavior What can you do with this object, or what methods can you apply
to it?
The objectsstate How does the object react when you apply those methods?
The objects identity How is the object distinguished from others that may have the same
behavior and state?
Classes:
The objects with the same data structure (attributes) and behavior (operations) are
grouped into a class. All those objects possessing similar properties are grouped into thesame unit.
Note on class:
A class is a template that unites data and operations
A class is an abstraction of the real world entities with similar properties
A class identifies a set of similar objects.
The class is an implementation of abstract data type
Relation between the classes
Dependence (uses-a)
The dependence, or usesa relationship, is the most obvious and also the most
general. For example, the Order class uses the Account class because Order objects need to
access Account objects to check for credit status. But the Item class does not depend on the
7/28/2019 Program Paradigm unit i
4/20
Account class, because Item objects never need to worry about customer accounts. Thus, a
class depends on another class if its methods use or manipulate objects of that class
Aggregation(has a)
The aggregation, or hasa relationship, is easy to understand because it is concrete;
for example, an Order object contains Item objects. Containment means that objects of class
A contain objects of class B.
Inheritance (is-a)
The inheritance, or isa relationship, expresses a relationship between a more
special and a more general class. For example, a RushOrder class inherits from an Order
class. The specialized RushOrder class has special methods for priority handling and a
different method for computing shipping charges, but its other methods, such as adding items
and billing, are inherited from the Order class. In general, if class A extends class B, class A
inherits methods from class B but has more capabilities
Predefined Classes:
Because you cant do anything in Java without classes, you have already seen several
classes at work. However, not all of these show off the typical features of object orientation.
Take, for example, the Math class. You have seen that you can use methods of the Math
class, such as Math.random, without needing to know how they are implementedall you
need to know is the name and parameters (if any).
Constructors
To work with objects, you first construct them and specify their initial state. Then you
apply methods to the objects. In the Java programming language, you use constructors to
construct new instances. A constructor is a special method whose purpose is to construct and
initialize objects.
Constructors always have the same name as the class name. Thus, the constructor for
the Date class is called Date. To construct a Date object, you combine the constructor with
the new operator, as follows:
new Date()
This expression constructs a new object. The object is initialized to the current date
and time. If you like, you can pass the object to a method:
System.out.println(new Date());
7/28/2019 Program Paradigm unit i
5/20
Alternatively, you can apply a method to the object that you just constructed. One of
the methods of the Date class is the toString method. That method yields a string
representation of the date. Here is how you would apply the toString method to a newly
constructed Date object:
String s = new Date().toString();
Note: Avoids usage of the destructors.
Defining the Class
A class is defined by the user is data type with the template that helps in defining the
properties. Once the class type has been defined we can create the variables of that type using
declarations that are similar to the basic type declarations. In java instances of the classes
which are actual objects
Eg:
class classname [extends superclassname]
{
[fields declarations;]
[methods declaration;]
}
Field Declaration
Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called as instance variables.
Class Rectangle
{
int length;
int width;
}
Method Declaration
A Class with only data fields has no life, we must add methods for manipulating the data
contained in the class. Methods are declared inside the class immediate after the instance
variables declaration.
Eg:
class Rectangle
{
7/28/2019 Program Paradigm unit i
6/20
int length; //instance variables
int width;
Void getData(int x, int y) // Method Declartion
{
Length =x;
Width = y;
}
}
Creating the objects
An object in java essentially a block of memory, which contains space to store all the
instance variables.
Creating an object is also referred as instantiating an object.
Object in java are created using the new operator.
Eg:
Rectangle rec1; // Declare the object
Rec1 = new Rectangle //instantiate the object
The above statements can also be combined as follows
Rectangle rec1 = new Rectangle;
Accessing the class members
It is not possible to access the instance variable and the methods outside the class directly, to
do this we must use the concerned object and the dotoperator.
Eg:
Objectname.variablename = value;
Objectname.methodname(parameter list)
Objectname name of the object.
Variablename- name of the instance variable inside the object.
Methodname- method we wish to call.
There is an another approach without using the dotoperator , where we use getdata() it is
illustrated in the following figure.
7/28/2019 Program Paradigm unit i
7/20
Constructors
We have seen the two approaches of Dot and getdata methods to access the instance
variables, where we need to initialize the variables.
Here is an another approach, using the constructors
Constructor initializes the object when it is created
Constructor name and the class name were the same
The following figure gives the overview of the constructor method and how it was called in
the code, which is the parameterized constructor.
There is also an another constructor method called default constructor which wont take any
of the parameter it will automatically initialize the object variable with the default values at that
time
7/28/2019 Program Paradigm unit i
8/20
Methods
Methods are similar to functions or procedures that are available in other programming
languages.
Difference B/w methods and functions
Difference b/w method and function is method declared inside class,function can be declared
any where inside are out side class
Writing methods in java
if we had to repeatedly output a header such as:
System.out.println("GKMCET");
System.out.println("Allapakkam");
System.out.println("Meppedu Road");
We could put it all in a method like this:
public static void printHeader()
{
System.out.println("GKMCET");
System.out.println("Allapakkam");
System.out.println("Meppedu Road");
}
And to call it we simply write:
printHeader();
public class Invoice{
public static void main(String[] args){
// call our method in the main method
printHeader();
System.out.println("You owe us $47.00");
}
// declare the method outside the main method
// but inside the end curly bracket for the class
7/28/2019 Program Paradigm unit i
9/20
public static void printHeader()
{
System.out.println("GKMCET");
System.out.println("Allapakkam");
System.out.println("Meppedu Road");
}
}
Types of methods
There are two types of methods.
Instance methods are associated with an object and use the instance variables of that
object. This is the default. Static methods use no instance variables of any object of the class they are defined
in. If you define a method to be static, you will be given a rude message by the
compiler if you try to access any instance variables. You can access static variables,
but except for constants, this is unusual. Static methods typically take all they data
from parameters and compute something from those parameters, with no reference to
variables
class MyUtils{public static double mean(int[] p)
{int sum = 0; // sum of all the elements
for (int i=0; i
7/28/2019 Program Paradigm unit i
10/20
Static Methods
Why declare a methodstatic
The above mean() method would work just as well if it wasn't declared static, as long as it
was called from within the same class. If called from outside the class and it wasn't declared
static, it would have to be qualified (uselessly) with an object. Even when used within the
class, there are good reasons to define a method as static when it could be.
Documentation. Anyone seeing that a method is static will know how to call it.
Similarly, any programmer looking at the code will know that a static method can't
interact with instance variables, which makes reading and debugging easier.
Efficiency. A compiler will usually produce slightly more efficient code because no
implicit object parameter has to be passed to the method.
Calling static methods
There are two cases.
Called from within the same class
Just write the static method name.
Eg,
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
Called from outside the class
If a method (static or instance) is called from another class, something must be given
before the method name to specify the class where the method is defined. For
instance methods, this is the object that the method will access. For static methods,
the class name should be specified.
Eg,
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the class of
the object will be used.
7/28/2019 Program Paradigm unit i
11/20
Method overloading
Method with same name and different arguments is called method overloading.
Here is an example for this
public class Overload2{
void add(int m, int n)
{int sum = m + n;System.out.println( "Sum of a+b is " +sum);}void add(int a, int b, int c){
int sum = a + b + c;System.out.println("Sum of a+b+c is " +sum);}
}class overloadfunc
{
public static void main(String args[]){Overload2 obj = new Overload2();obj.add(4,19);obj.add(4,17,11);
}
Access specifiers
Public
It can be accessed from anywhere.
Friendly
It is also known as default, the difference between public and friendly is public can be
accessed from any package whereas friendly is accessed with the packages only.
Protected
It lies between public and friendly, this makes visible all classes and sub classes with
in the same package and also to subclasses in other packages.
Private
It is the highest degree of protection, which is accessible within own class alone.
7/28/2019 Program Paradigm unit i
12/20
Private protected
Its level is between private and protected, it makes accessible to all subclasses
regardless of the packages.
Static Members
Let us assume that we want to define a member that is common to all the objects and
can be accessed without using a particular object. That is the member belongs to the class
as a whole rather than the objects created from the class.
It can be defined as follows
static int count;
static int max (int x, int y);
The members declared as static are known as static members.
Static variable are used when we want to have a variable common to all instances of
class.
Eg: Using static members
7/28/2019 Program Paradigm unit i
13/20
Final methods and variables
All method and variables can be overridden by default subclasses. If we wish to
prevent the subclasses from overriding the members of the superclass, we can declare
them as final using the keyword final as a modifier.final int SIZE = 100;
final void showstatus()
Making a method final ensures that the functionality defined in this method will never
be altered in anyway, similarly the value of a final variable can never be changed.
Finalizer methods
In java we know that Garbage collector will automatically frees the memory resources
used by objects. But objects may hold other non object resources such as file descriptor
or window system fonts. The Garbage collector cannot free those resources. To facilitate
this java provides this finalizer method, similar to destructor in C++.
The finalizer method is simply finalize() and can be added to any class.
Finalize method should explicitly specify the operation to be performed.
Arrays
An array is a data structure that stores a collection of values of the same type. You
access each individual value through an integerindex.
Array Name [index]
Integer constant, variable, or expression
For Instance we can define an array name salary to represent a set of salaries of a
group of employees. A particular value is indicated by writing a number called index in
brackets after the array name.
salary [10]
it represents the salary of the 10th employee.
7/28/2019 Program Paradigm unit i
14/20
Types of arrays
One dimensional arrays
Two dimensional arrays
One Dimensional arrays
A list of items can be given one variable name using only one subscript and such a
variable is called single- subscripted of one dimensional array. The subscript can also start
from 0. ie x[0].
If we want to represent a set of five numbers, say (35,40,20,57,19) by an array
variable number, then we have to create the variable number as follows
int number [ ] = new int [5 ];
and the computer reserves the memory space in the following way.
The value to the array elements can be assigned as follows
Number [0] =35;Number [1] =40;
Number [2] =20;
Number [3] =57;
Number [4] =19;
This would cause the array number to store the values shown as follows;
Number [0]
Number [1]
Number [2]
Number [3]
Number [4]
7/28/2019 Program Paradigm unit i
15/20
Creating an array
Declaring the array
Creating memory locations
Putting values into the memory locations.
Declaring the Array
Array in java can be declared in two forms
Form 1 type arrayname [ ];
Form 2 type [ ] arrayname;
Creation of arrays
arrayname = new type [ size ];
Eg;
number = new int [5] ;
average = new float[10];
it is also possible to combine declaration and creation.
int number [ ] = new int [5];
Initialization of arrays
The final step is to put values into the array created. This process is known as
initialization using the array subscripts as shown below.
arrayname[subscript] = value ;
Eg
number[0] = 15;
we can also initialize by following way
type arrayname [ ] = { list of values }
Array Length
7/28/2019 Program Paradigm unit i
16/20
All array store the allocated size in an variable named length. We can obtain the
length of array a using a.length
Eg:
int asize = a.length;
Sample Code for array manipulation
Two Dimensional arrary:
Usage : int myArray [ ] [ ];
myArray = new int [3] [4];
or
init myArray [ ] [ ] = new int [3][4]
This creates a table that can store 12 integer values, four across and three down.
Strings:
Series of characters represents a string, and easiest way to represent the string is array
Eg:
Char charArray [ ] = new char [2] ;
charArray[0] = j ;
charArray[1] = a ;
String can be declared and created in the following way
string stringname;
stringname = new string (string);
Operations on string
int m = stringname.length() //will return the length of the string
string city = New + Delhi// will return New Delhi ,string concatinating
7/28/2019 Program Paradigm unit i
17/20
Packages
Packages are javas way of grouping a variety of classes and/or interfaces together.
Java API Packages
Using system packages.
7/28/2019 Program Paradigm unit i
18/20
We may like to use many of the classes contained in a package.it can be achieved by
Import packagename . classname
Or
Import packagename.*
Creating the package
To create our own packages
package firstpackage;// package declaration
public class FirstClass //class definition
{..
(body of class)
.}
The file is saved as FirstClass.java,located at firstpackage directory. when it is compiled
.class file will be created in same ditectory.
Access a package
The import statement can be used to search a list of packages for a particular class. The
general form ofimport statement for searching class is a as follows.
Package name
7/28/2019 Program Paradigm unit i
19/20
Import package1 [.package2] [.package3].classname;
Using the package
package package1 ;
public class classA
{
public void displayA()
{
System.out.println(class A);
}
}
Adding a class to package
Define the class and make it public
Place the package statement
Package P1
Before the class definition as follows
Package p1;
Public class B
{
// body of B }
Overview of Javadoc
The basic structure of writing document comments is embed them inside /** ... */.
The Javadoc is written next to the items without any separating newline. The class
declaration usually contains:
public class Test {
// class body
}
(1) a short, concise, one line description to explain what the itemdoes. This is followed by[2] a longer description that may span in multiple paragraphs. In those the details can be
explained in full. This section, marked in brackets [], is optional.
(3) a tag section to list the accepted input arguments and return values of the method.
7/28/2019 Program Paradigm unit i
20/20
Variables are documented similarly to methods with the exception that part (3) is omitted.
Here the variable contains only the short description:
Tag & Parameter Usage Applies to Since
@authorname Describes an author. Class, Interface
@versionversionProvides version entry. Max one perClass or Interface.
Class, Interface
@sincesince-textDescribes since when this functionalityhas existed.
Class, Interface,Field, Method
@seereferenceProvides a link to other element ofdocumentation.
Class, Interface,Field, Method
@paramnamedescription
Describes a method parameter. Method
@returndescription Describes the return value. Method
@exceptionclassnamedescription
@throwsclassnamedescription
Describes an exception that may bethrown from this method.
Method
@deprecateddescription Describes an outdated method. Method
{@inheritDoc}Copies the description from theoverridden method.
Overriding Method 1.4.0
{@linkreference} Link to other symbol.Class, Interface,Field, Method
{@value} Return the value of a static field. Static Field 1.4.0
Top Related