OOPs Mat V2 engineering108.com, Lecture notes of Java Programming

This book will be helpful for oops concepts

Typology: Lecture notes

2012/2013

Uploaded on 04/05/2013

om.prakash1
om.prakash1 🇮🇳

1 document

1 / 51

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
OOPS
1
Version - 2.01
31st Mar 2005
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33

Partial preview of the text

Download OOPs Mat V2 engineering108.com and more Lecture notes Java Programming in PDF only on Docsity!

Version - 2.

st

Mar 2005

Table Of Contents

    1. Introduction to OOPs...................................................................................
    1. Benefits of OOPs.........................................................................................
    1. Features of OOPs.........................................................................................
    1. Encapsulation and Data Abstractions
    1. Constructors and Destructors
    • Constructors
    • Destructors
    • Static Class Data
    1. Types of variables
    • Classes, objects and memory
    1. Polymorphism
    1. Inheritance..................................................................................................
    • Derived and Base Classes
    1. Polymorphism in Inheritance
    • Overriding Member Functions...................................................................
    1. Abstract classes & Functions

2. Benefits of OOPs

Why Object Oriented Languages?

People who are new to any object oriented language or who are trying to learn about it from books, often have two major questions:

  • "Everything I read always has this crazy vocabulary--'encapsulation', 'inheritance', 'virtual functions', 'classes', 'overloading', 'friends'-- Where is all of this stuff coming from?" and
  • "This language--and object oriented programming in general--obviously involve a major mental shift, so how do I learn to think in a C++ way?"

Both of these questions can be answered, and the design of OOP as a whole is much easier to swallow, if you know what the designers of C++(the first full-fledged object oriented language) were trying to accomplish when they created the language. If you understand why the designers made the choices they did, and why they designed certain features into the language, then it is much easier to understand the language itself.

Lets first see problems with Structured Programming:- As programs grow larger and compiles, the structured programming approach fails. Analyzing the reasons for these failures reveals that there are weaknesses in the procedural paradigm itself. No matter how well the structured programming approach is implemented, large programs become excessively complex.

In a procedural language, the emphasis is on doing things – read the keyboard, check for errors and so on. i.e. emphasis is on action. Data is given a second class treatment.

In procedural languages, we declare global variables; these variables can be accessed by all functions. These functions can perform various operations on the data. You may declare local variables, but they cannot be accessed by all functions.

Now suppose a new programmer is hired to write a function to analyze the data in a certain way. Unfamiliar with the program, the programmer may create a function that accidentally corrupts the data. This is possible because the function has complete access to the data.

Another problem is that since many functions access the same data, the way the data is stored becomes critical. The arrangement of the data cannot be changed without modifying all the functions that access it.

What is needed is a way to restrict access to the data, to hide it from all but a few critical functions. This will protect the data and simplify maintenance.

Procedural programs are often difficult to design. The problem is that their chief components - functions and data structures – do not model the real world very well.

With traditional languages, there is a problem of creating new data types. You cannot bundle both X and Y into a single variable called Point and then add and subtract values.

Unlike structures approach the OOP approach always model the real world well. OOP always talk in terms of the objects, wherein the procedure oriented approach talk in terms of instructions or steps to be carried out. In simple word, OOP give more emphasis on data and procedure oriented approach give more emphasis to instructions. To take a simple example, suppose I want to tell somebody , how did I get a book from library. The procedure oriented approach would expect to write down following steps:-

  1. Start from your desk.
  2. Start walking in the direction of the library.
  3. Cross the corridor.
  4. Enter the library.
  5. Ask for the book
  6. Get the book In the above mentioned steps, actually what is important is a person, a library and a book. But these things are lost in the long procedure. Same thing can be explained in the OOP terminology as, I went to library and got a book. The instructions are not given any importance rather they are included in the objects i.e. instructions (functions or methods) related to the book are embedded in the book object and so on. In real life also, we give emphasis to data rather than the instructions. That’s how modeling real life problems is easy in OOP.

4. Encapsulation and Data Abstractions

Encapsulation:- The primitive element of object-oriented programming is an object. A object contains certain information, and knows how to perform certain operations. Objects, which share the same behavior, are said to belong to the same class. A class is a generic specification for an arbitrary number of similar objects. You can think of a class as a template for a specific kind of objects, or as a factory, cranking out as many products as required. A class can also be treated as a user defined data type. A C++ class syntactically appears similar like structures in C. Encapsulation is a mechanism that binds together code and data, and that keeps both safe from outside interference or misuse. Further, it allows the creation of an object. An object is a logical entity that encapsulates both data and the code that manipulates that data. When you define an object, you are implicitly creating a new data type. Encapsulation draws a capsule around related things.

Figure 4.1 Encapsulation

Class Data Members ( Information ) and Members Function ( Operations ) Data members are also called as properties of the object. Function members are also called as methods.

Figure 4.2 A complete class

Data Members/ Member Variables

Member Functions

Information + Operations

CLASS VEHICLE

int engine-no; int vehicle-no; String manufacturer ……. Accelerate() Change-gears() ……..

Abstraction :- The object has one more peculiar property , data abstraction. The object has a public interface and a private representation , and keeps as information hiding. Information hiding distinguishes ability to perform some act from the specific steps taken to do so. Publicly , an object reveals its abilities: “I can do these things” , it declares, and “I can tell these things.” But it does not tell how it knows or does them, nor need other objects concern themselves with that. Instead, another object requesting an operations or some information acts like a good manager. It specifies the job or asks for the information and then leaves. It doesn’t hang around worrying about how the job is done or how the information is calculated. Objects know only what operations they can request other objects to perform. This helps you take a somewhat abstract view of the object as you design it. Some details do not yet concern you , and can be deferred. You can concentrate on the essence of your design. Another gain comes later in the lifetime of the system. You can change the internal representation of an object or implement a superior algorithm for a specific operation without changing the object’s abstract, public interface.

Figure 4.3 Data Abstraction ( Information Hiding)

Encapsulation and information-hiding work together to isolate one part of the system from other parts, allowing code to be modified and extended, and bugs to be fixed, without the risk of introducing unnecessary and unintended side-effects. Objects are a way of putting these two principles to practical use in a program.

  1. First you abstract out the functionality and information that are related, that belong together, and encapsulate them in one object.
  2. Then you decide what functionality and information other objects will require of that objects. The rest you hide. You design a public interface ( the outside of the capsule) that allows other objects to access what they require. The private representation ( the inside of the capsule) is by default protected from access by other objects.

How can I relate these concepts with real life examples. Data abstraction means the interface is available to the external world for the access, but internal details are hidden. We all ride or drive different kind of vehicles. To operate the vehicle we are given different parts like brake, handle, accelarator etc. These parts are nothing but the interfaces. We use the vehicle with the help of the interfaces, without knowing the internal structure of the machine (data abstraction!). Now the internal functioning of brake or any other part can be changed without changing the external appearance. So

Public Interface

Private representation

It means a variable to the data type is same as an object to the class.

Here class serves as a plan, or template. It specifies what data and what functions will be included in objects of that class. Defining the class does not create any objects, just as mere existence of a type int does not create any variable. Hence we have 2 object of class vehicle, having the attributes like engine-no, vehicle-no, manufacturer and functions like accelerate() and change-gears().

Observe here that the properties and functions of a class vehicle are automatically become a part of object, but the value that each property holds for two different object is different. For example, Opel manufactured John’s car. while Ford manufactures Sam’s car, but both objects have a property called as manufacturer.

Figure 4.5 Actual representation of class and object

Specifying the Class

All said and done about what is a class and what is an object, let us see the basic syntax for writing the class.

CLASS VEHICLE

int engine-no; int vehicle-no; String manufacturer ……. Accelerate() Change-gears() ……..

John’s VEHICLE

int engine-no : 1234 int vehicle-no : 3456 String manufacturer : OPEL ……. Accelerate() Change-gears() ……..

Sam’s VEHICLE

int engine-no : 7890 int vehicle-no : 4567 String manufacturer : FORD ……. Accelerate() Change-gears() ……..

The general format for writing the classes is:

class <class-name> { data-type variable1; data-type variable2; data-type variable3;

data-type <function-name> ( function arguments) { }

data-type <function-name> ( function arguments) { }

Note: This is a generalized format to write a class. The actual syntax might differ a little bit from language to language.

So let us write concrete definition of class Vehicle that we have been representing diagrammatically until now.

class Vehicle {

int engineNo; int vehicleNo; String manufacturer;

//function Accelerate public void Accelerate () { //some code here }

//function change-gears public void Change-gears() { //some code here } } // class ends.

Class Data

The vehicle class contains three data members: engineNo, vehicleNo of data type int and manufacturer of data type String. There can be any number of data items in a class. The data items might precede with some visibility modifier / access specifier depending upon the language used.

In some of the OOP languages like C++, polymorohism can be implemented using operator overloading. This concept is not supported by Java. Operator overloading allows you to manipulate objects as, basic data types. If I have a date class, containing some date, a minus operator can be overloaded to find out difference between two dates.e.g. Date d1, d2,d3; D3= d1 - d2; In this example d1,d2 and d3 are date objects. d1 and d2 are subtracted to give d3. Now without overloading the operator , such subtraction is not possible.

Using the Class Now that the class is defined, let us discuss the possible ways to use any class or members of that class. Any class can be used only in two fashions:

  • Instantiate the class and create the object
  • Write a different class inheriting from that class

This chapter explains the how to create objects from the class and call its member functions while inheritance will be described in the next chapter.

Defining Objects The first statement in main(),

Vehicle v_john = new Vehicle(); Vehicle v_sam = new Vehicle();

defines two objects, v_john and v_sam, of class vehicle. Remember that the specification for the class Vehicle does not create any objects. It only describes how they will look when they are created. Defining an object is actually defining a variable of any data type: Space is set-aside for it in memory. Calling Member Functions

The next two statements in main() call the member function setVehicleNo():

v_john. setVehicleNo(3456); v_sam. setVehicleNo(4567);

These statements don’t look like a normal function calls. This strange syntax is used to call a member function that is associated with a specific object. Because setVehicleNo() is a member function of the Vehicle class, it must be called in connection with an object of this class. It doesn’t make sense to say

setVehicleNo(1234);

by itself, because member function is always called to act on a specific object, not on class in general. Attempting to call a method like that will produce a compiler error.

Note: only an object of that class can access Member functions of the class.

5. Constructors and Destructors

Constructors

Constructors are nonstatic member functions that determine how the object of a class is created, initialized and copied. A constructor executes automatically when an object is created. Constructors are also invoked when local or temporary objects of a class are created.

The constructor can be overloaded to accommodate many different forms of initalizations for instances of the class. The execution of the contructor does not reserve memory for the instance itself. The compiler generates the code to do this, either in static memory, on the stack, or on the heap, after which control is handed over to the constructor to do the initialization of the data members.

Rules for Constructors :

  • Name of Constructors should be the same as name of the class to which it belongs.
  • It is declared with no return type not even void.
  • It cannot be declared as static or const.
  • It should have public or protected access.
  • Constructors can be overloaded

When the Constructor is called :

An instance of some class comes into existence and causes the constructor function to be invoked when

  • A global or static local variable of the class is defined ( the constructor is called before main( )).
  • An auto variable of the class is defined within a block and the location of its definition is reached.
  • A temporary instance of the class needs to be created.
  • An instance of the class is obtained from free memory via the new operator.
  • An instance of some class is created that contains, as a data member, an instance of the class.
  • An instance of some class derived from the class is created.

class Box { private:

//parameterized constructors Box( int a) { width = a; height = a; }

Box(int a, int b) { width = a; height = b; }

void showDetails() { cout << “Width = “ << width; cout << “Height = “ << height; } }

void main() { Box b1, b2(5),b3(10,12); b1. showDetails(); b2. showDetails(); b3.showDetails(); }

Example 5.2 Parameterized constructor (C++)

Here in the examples above, we are writing three different constructors, for the box class. This kind of technique is called as function overloading. Which function to call is decided upon the kind of parameters passed while calling the function. For example, in the code above we are creating three objects of Box class, b1,b2 and b3.

Box b1; // this declaration calls the first constructor.

Box b2(5); // this declaration calls the second constructor which gets one integer value.

Box b2(5); // this declaration calls the second constructor witch expects two integer values.

The result of this program will be:

Box b1: width = 0, height= 0 Box b2: width = 5, height= 5 Box b1: width = 10, height= 12

The first constructor with no arguments, is called as a default constructor of the class. The other two constructors are called as parameterized constructors. This is a specific example of constructor overloading. The same technique is applicable to any other functions in the class.

Destructors

A destructor is a function, which is called automatically whenever an instance of the class goes out of existence. The destructor is used to release space on the heap that the instance currently has reserved.

Rules for Destructors

  • Its name is the same as that of the class to which it belongs, except that the first character of the name must be a tilde(~).
  • It is declared with no return type, not even void, since it cannot return a value.
  • It cannot be declared static or const.
  • It takes no input arguments, and so cannot be overloaded.
  • It should have public access in the class declaration.

When a destructor function is called

The destructor function for a class is called :

  • After the end of main( ) for all static, local to main( ), and global instances of the class.
  • At the end of each block containing an auto variable of the class.
  • At the end of each function containing an instance of the class as argument.
  • To destroy any unnamed temporary instances of the class after their use.
  • When an instance allocated on the heap is destroyed via delete.
  • When an object containing an instance of the class is destroyed.
  • When an object of a class derived from the class is destroyed.

Static Class Data

Having said that each object contains its own separate data, we must amend that slightly. If a data in a class is defined as static, then only one such item is created for the entire class, no matter how many objects are created from that class. Static item is useful when all the objects of the same class need to share a common item of information.

As an example, suppose an object needs to know how many other objects of its class were in the program. We can use a static data member over here to fulfill the functionality.

Class item { static int count ; int number ; public :

void getdata(int a){ number = a; count ++; } void getcount (void) { cout << “count: “ ; cout << count << “\n” ; } } ; int item :: count ; main () { item a , b ; a.getcount(); b.getcount(); a.getdata(); b.getdata() ; cout << “After reading data “; a.getcount(); b.getcount(); } Example 5.4 Static class data in C++

6. Types of Variables

Let us again have a look at the method addTwoBoxes() from previous example.

Box addTwoBoxes(Box b) { int x = width + b.width; int y = height + b.height; int z = depth + b.depth; Box newb = new Box(x, y, z); Return newb; }

The number of variables used by this particular function are b, x, y, width, height and so on. These all variables are bifurcated into two categories:

  • Local Variables
  • Instance Variables

Local Variable

The variables declared within a function or method or any block of code and the arguments passed to a function are called as local variables. The scope of all the local variables is with that block. It simply means that, the local variables are not accessible outside the block, in which they are defined.

Box addTwoBoxes(Box b) { /* width, height, depth : instance variables x, y, z, b, newb : local variables / int x = width + b.width; int y = height + b.height; int z = depth + b.depth; Box newb = new Box(x, y, z); Return newb; } int volume() { return xy*z; // will produce a an error as x, y and z are not available. }