pgm paradigm

34
Lecture Plan Code : CS2305 Issue : CRev : 01 Subject : Programming Paradigms Page : 1 of 2 Unit No : 1 Period : 1/9 Programming Paradigm- A programming paradigm is a fundamental style of computer programming Review OOP Definition of oop 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

Upload: chithambaram-nanban

Post on 26-Oct-2014

83 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Pgm Paradigm

Lecture Plan

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 2

Unit No : 1 Period : 1/9

Programming Paradigm-

A programming paradigm is a fundamental style of computer programming

Review OOP

Definition of oop

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.

Page 2: Pgm Paradigm

Page: 2 of 2

Other concepts of oops

Message passing

Extensibility

Persistence

Delegation

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 is far 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 of large project

Garbage collection

No destructor code needed

No cross-compilation needed

Advantages of java Protable Secure Simple Network savyJava Virtual Machine

Sample Java Code:public class HelloWorld { // method main(): ALWAYS the APPLICATION entry point public static void main (String[] args) {

System.out.println ("Hello World!"); }}**Java Case Sensitive

Lecture Plan

Java Program Java Complier Virtual Machine

Process of Compilation

Source Code Byte Code

Page 3: Pgm Paradigm

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 3

Unit No : 1 Period : 2/9

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.

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 object’s behavior What can you do with this object, or what methods can you apply

to it?

• The object’s state How does the object react when you apply those methods?

• The object’s identity How is the object distinguished from others that may have the same

behavior and state?

Page : 2 of 3

Page 4: Pgm Paradigm

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 the

same 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 “uses–a” 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

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 “has–a” 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 “is–a” 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

Page 5: Pgm Paradigm

Page : 3 of 3

Predefined Classes:

Because you can’t 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 implemented—all 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());

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.

Page 6: Pgm Paradigm

Lecture Plan

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 2

Unit No : 1 Period : 3/9

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.

Page 7: Pgm Paradigm

Page : 2 of 2

Eg:

class Rectangle

{

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;

Lecture Plan

Page 8: Pgm Paradigm

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 2

Unit No : 1 Period : 4/9

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 dot operator.

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 dot operator , where we use getdata() it is

illustrated in the following figure.

Application of classes and objects

Page : 2 of 2

Page 9: Pgm Paradigm

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

Application of Constructor

Lecture Plan

Page 10: Pgm Paradigm

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 3

Unit No : 1 Period : 5/9

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");

}

Page : 2 of 3

Page 11: Pgm Paradigm

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

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

Page : 3 of 3

Page 12: Pgm Paradigm

Here is a typical static method.

class MyUtils {

public static double mean(int[] p) { int sum = 0; // sum of all the elements for (int i=0; i<p.length; i++) { sum += p[i]; } return ((double)sum) / p.length; }//endmethod mean . . .}

Lecture Plan

Page 13: Pgm Paradigm

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 3

Unit No : 1 Period : 6/9

Static Methods

Why declare a method static

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 meth

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.

Page : 2 of 3

Page 14: Pgm Paradigm

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.

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.

Page : 3 of 3

Page 15: Pgm Paradigm

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.

Private protected

Its level is between private and protected, it makes accessible to all subclasses

regardless of the packages.

Lecture Plan

Page 16: Pgm Paradigm

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 2

Unit No : 1 Period : 7/9

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

Page : 2 of 2

Page 17: Pgm Paradigm

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.

Lecture Plan

Page 18: Pgm Paradigm

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 4

Unit No : 1 Period : 8/9

ArraysAn array is a data structure that stores a collection of values of the same type. You

access each individual value through an integer index.

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.

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.

Page 19: Pgm Paradigm

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;

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;

Page : 3 of 4

Number [0]

Number [1]

Number [2]

Number [3]

Number [4]

Page 20: Pgm Paradigm

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

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.

Page : 4 of 4

Page 21: Pgm Paradigm

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

Sample Code for string manipulation

Lecture Plan

Page 22: Pgm Paradigm

Code : CS2305 Issue : CRev : 01

Subject : Programming Paradigms Page : 1 of 4

Unit No : 1 Period : 9/9

Packages

Packages are java’s way of grouping a variety of classes and/or interfaces together.

Java API Packages

Using system packages.

Page : 2 of 4

Page 23: Pgm Paradigm

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 of import statement for searching class is a as follows.

Import package1 [.package2] [.package3].classname;

Using the package

package package1 ;

public class classA

{

public void displayA()

{

System.out.println(“class A”);

}

}

Page : 3 of 4

Package name

Page 24: Pgm Paradigm

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:

/**

* @author Firstname Lastname <address @ example.com>

* @version 1.6 (The Java version used)

* @since 2010.0331 (E.g. ISO 8601 YYYY.MMDD)

*/

public class Test {

// class body

}

For methods there is

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

/**

Page 25: Pgm Paradigm

* Short one line description. (1)

*

* Longer description. If there were any, it would be [2]

* here.

*

* @param variable Description text text text. (3)

* @return Description text text text.

*/

Variables are documented similarly to methods with the exception that part (3) is omitted.

Here the variable contains only the short description:

/**

* Description of the variable here.

*/

private int debug = 0;

Tag & Parameter Usage Applies to Since@author name Describes an author. Class, Interface

@version versionProvides version entry. Max one per Class or Interface.

Class, Interface

@since since-textDescribes since when this functionality has existed.

Class, Interface, Field, Method

@see referenceProvides a link to other element of documentation.

Class, Interface, Field, Method

@param name description

Describes a method parameter. Method

@return description Describes the return value. Method@exception classname description@throws classname description

Describes an exception that may be thrown from this method.

Method

@deprecated description Describes an outdated method. Method

{@inheritDoc}Copies the description from the overridden method.

Overriding Method 1.4.0

{@link reference} Link to other symbol.Class, Interface, Field, Method

{@value} Return the value of a static field. Static Field 1.4.0