Object Oriented Programming through Java

Size: px
Start display at page:

Download "Object Oriented Programming through Java"

Transcription

1 Object Oriented Programming through Java

2 Board of Studies Prof. H. N. Verma Vice- Chancellor Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune Prof. M. K. Ghadoliya Director, School of Distance Education and Learning Jaipur National University, Jaipur Subject Expert Panel Dr. Ramchandra G. Pawar Director, SIBACA, Lonavala Pune Ashwini Pandit Subject Matter Expert Content Review Panel Gaurav Modi Subject Matter Expert Shubhada Pawar Subject Matter Expert Copyright This book contains the course content for Object Oriented Programming through Java. First Edition 2013 Printed by Universal Training Solutions Private Limited Address 05 th Floor, I-Space, Bavdhan, Pune All rights reserved. This book or any portion thereof may not, in any form or by any means including electronic or mechanical or photocopying or recording, be reproduced or distributed or transmitted or stored in a retrieval system or be broadcasted or transmitted.

3 Index I. Content...II II. List of Figures...VI III. List of Tables... VII IV. Abbreviations...VIII V. Application VI. Bibliography VII. Self Assessment Answers Book at a Glance I

4 Contents Chapter I... 1 Object Oriented Programming with Java... 1 Aim... 1 Objectives... 1 Learning outcome Introduction to OOP Object Oriented Programming Concepts Object Oriented Programming Programming Paradigm Functional Programming Logic Programming Object Orientation as a New Paradigm: The Big Picture Messages and Responsibilities Classes and Instances Objects and Classes Encapsulation Messages Classes Types Summary References Recommended Reading Self Assessment Chapter II Classes, Objects and Methods Aim Objectives Learning outcome Introduction Defining a Class Fields Declaration Methods Declaration Creating Objects Accessing Class Members Constructors Summary References Recommended Reading Self Assessment Chapter III Inheritance Aim Objectives Learning outcome Introduction to Inheritance Example of Inheritance Derivation Syntax Effects of Inheritance Protected Access Overriding Methods Dynamic Method Dispatching II

5 3.3.2 The Super Keyword Final Methods and Final Classes Constructor Chaining Inheritance and Finalization Abstract Classes Interfaces The Implements Declaration Casting between Class Types Summary References Recommended Reading Self Assessment Chapter IV Polymorphism Aim Objectives Learning outcome Introduction to Polymorphism Upcasting Revisited Forgetting the Object Type Method Calling Binding Producing the Right Behaviour Extensibility Overriding vs Overloading Abstract Classes and Methods Constructors and Polymorphism Order of Constructor Calls Summary References Recommended Reading Self Assessment Chapter V Exception Handling Aim Objectives Learning outcome Introduction to Exception Handling Dealing with Errors The Classification of Exceptions Advertising the Exceptions that a Method Throws How to Throw an Exception Creating Exception Classes Catching Exceptions Catching Multiple Exceptions Rethrowing Exceptions Summary References Recommended Reading Self Assessment III

6 Chapter VI Object Oriented Programming Aim Objectives Learning outcome Introduction to OOP Class Object Method Basic Concepts of Object Oriented Programming Objects Classes Data Abstraction and Encapsulation Inheritance Polymorphism Dynamic Binding Message Passing Paradigms of Programming Languages Imperative Paradigms Declarative Paradigm Programming Procedural Programming Modular Programming Data Abstraction Object Oriented Programming Objects Object: The Soul of Object Oriented Programming The Object Orientation Classes A Complete View of a Class Scope Operator Scope of Class and its Members Object Oriented Programming Object Oriented Programming Characteristics Advantages of Object Oriented Programming Summary References Recommended Reading Self Assessment Chapter VII Classes and Objects Aim Objectives Learning outcome Introduction to Classes Specifying a Class Creating Objects Defining Member Functions Static Data Members Static Member Functions Const Member Functions Pointer to Members Constructor Copy Constructor IV

7 7.9 Destructors Summary References Recommended Reading Self Assessment Chapter VIII Operator Overloading Aim Objectives Learning outcome Introduction to Operator Overloading How to Overload Operators Overloading Unary Operators Overloading Binary Operators Rules for Overloading Operators Types Conversions Summary References Recommended Reading Self Assessment Chapter IX Inheritance, Multiple Inheritance and Polymorphism Aim Objectives Learning outcome Introduction to Inheritance Defining Derived Classes Single Inheritance Multiple Inheritances Polymorphism Summary References Recommended Reading Self Assessment V

8 List of Figures Fig. 1.1 Inheritance... 4 Fig. 1.2 Objects... 9 Fig. 1.3 Messages Fig. 2.1 Creating object references Fig. 2.2 Assigning one object reference variable to another Fig. 3.1 Accessibility in an inheritance relationship Fig. 3.2 Constructor chaining Fig. 3.3 The relationship between an abstract class and its derived classes Fig. 4.1 Inheritance diagram Fig. 4.2 Addition of methods and classes to the instrument Fig. 4.3 Instrument class into abstract class Fig. 5.1 Exception hierarchy in Java Fig. 6.1 Property inheritance Fig. 6.2 Polymorphism Fig. 6.3 Message passing Fig. 6.4 Language paradigm Fig. 6.5 Programming paradigms Fig. 6.6 Objects and interfaces Fig. 6.7 Communication between objects Fig. 6.8 An object Fig. 7.1 Representation of a class Fig. 9.1 Adding more members to a class (by public derivation) Fig. 9.2 Adding more members to a class (by private derivation) Fig. 9.3 Multiple inheritance Fig. 9.4 Polymorphism VI

9 List of Tables Table 3.1 Access to class A s members Table 6.1 Procedural and object oriented paradigms Table 6.2 Functional and logical paradigms Table 8.1 Operators that cannot be overloaded Table 8.2 where a friend cannot be used VII

10 Abbreviations ADT - Abstract Data Types API - Application Programming Interface I/O - Input/output OOP - Object Oriented Programming Prolog - Programming in Logic URL - Universal Resource Locator VIII

11 Chapter I Object Oriented Programming with Java Aim The aim of this chapter is to: introduce the concept of OOP explain the theory of inheritance in Java elaborate the concept of abstraction explain polymorphism in Java Objectives The objectives of this chapter are to: get an overview of encapsulation used in Java explain the significance of events in Java discuss programming paradigms in Java discuss functional programming Learning outcome At the end of this chapter, you will be able to: understand the messages and responsibilities of Java describe objects and classes in Java evaluate various types of the Java 1

12 Object Oriented Programming through Java 1.1 Introduction to OOP Object Oriented Programming, also known as OOP, is a computer science term which is used to describe a computer application that is composed of multiple objects which are connected to each other. Traditionally, most computer programming languages were simply a group of functions or instructions. With OOP, every object can handle data, get messages, and transfer messages to other objects. The objects will all act as independent units in their own right, and they will be responsible for carrying out a certain process. Because the objects are not dependent on each other, OOP is seen as being more flexible than older methods of programming. It has become quite popular, and it is now used in a number of advanced software engineering projects. Many programmers feel that object oriented programming is easier for beginners to learn than previous programming methods. Because it is easier to learn, it can also be analyzed and maintained without a large amount of difficulty. However, there are some people who feel that OOP is more complicated than older programming methods. To understand object oriented programming, there are a few concepts we need to become familiar with. A. The first concept that we need to learn is called a class A class creates the attributes of a thing, and it will also define the processes that the thing can carry out. For example, a class called cats will have the attributes which are commonly found with cats, such as the ability to purr. A class will bring about modularity within the objected oriented computer application. Someone who is not a programmer should be able to find a class The reason for this is because the attributes of the class should be something that will make sense to them. It is also important for the code of a class to be self contained to a certain degree. When code is written with relevant names, it will be easier to understand. Making sure the code is self-contained will allow one part of the application to be updated without needing to change the other parts. It is this modularity that makes OOP an effective programming method. It will also help the application solve the problems that it was designed for. B. The next concept that we need to be familiar with is an object An object can be defined as a specific instance of a class. As an example, while the class Cats will provide all the attributes that are found in all cats, the object named Betsy is a specific cat. While it shares the same attributes which are found in all cats, it has fur with a unique colour. In object oriented programming, a programmer would say that the object Betsy is a run-time instance of the class Cats. A class may also be divided into sub-groups. Certain variations of a class may not be a specific object. The class Cats may have a sub-group which consists of multiple cat breeds. For example, if Betsy were a Persian cat, it would be an instance of the Persian cat sub-group. some attributes with the parent class, but it will also have unique attributes as well. Every object within an OOP language will share. C. The next concept that we want to be familiar with is method A method may also be called a message and can be defined as the abilities of an object. Because Betsy is a cat, Betsy can purr. Because of this, purr is a method that Betsy has. Betsy may have a number of other methods. When a method is used within an object oriented programming language, it will only affect a single object. This is true even if the method is designed for the entire class. 2

13 While all cats can purr, we will need only one cat to do it. Methods can further be broken down into commands, call-backs, or queries. A query will tell us about the state of the object, and a command will cause that object to carry out a task. A call-back is a method that is composed of a part within an object. The part will notify its parent that an event has taken place, and the object may need to react to the eve 1.2 Object Oriented Programming Concepts Three of the most basic concepts for object oriented programming are classes, objects, and methods. However, there are a few more concepts that we need to be familiar with. They are: Inheritance Abstraction Polymorphism Event Encapsulation We will be using the class Cats as an example throughout the chapter. Inheritance Inheritance will allow a sub-group to make a connection with the associates of its parent class. For example, let s say the class Cats decides to create a method called purr() and a property named Colorfur. As the name implies, a property is a specific attribute which is connected to an object. Every sub-group will be able to inherit the associates, and this means the developer only needs to create the code for them one time. The traits that are inherited by the sub-group can be changed. For example, the Persian cat class may choose to make the Colorfur white for their default colour. In contrast, another cat breed may choose a different Colorfur trait. It is also possible for the sub-group to add new associates. If a specific cat Class sub-group wants to set a default eye colour, this can be inherited as well. Some object oriented programming languages may also allow a class to inherit traits from multiple ancestors, and this is called multiple inheritance. Some programs may not allow this. One object-oriented concept that helps objects work together is inheritance. Inheritance defines relationships among classes in an object-oriented language. In the Java programming language, all classes descend from java.lang.object and implement its methods. The following diagram shows the class hierarchy as it descends from java.lang.object for the classes in the user interface example above. The java.lang.object methods are also shown because they are inherited and implemented by all of its subclasses, which is every class in the Java API libraries. Java.lang.Object defines the core set of behaviours that all classes have in common. As we move down the hierarchy, each class adds its own set of class-specific fields and methods to what it inherits from its superclass or superclasses. The java.awt.swing.jframe class inherits fields and methods from java.awt.frame, which inherits fields, and methods from java.awt.container, which inherits fields and methods from java.awt.component, which finally inherits from java.lang.object, and each subclass adds its own fields and methods as needed. 3

14 Object Oriented Programming through Java Java.lang.Object clone() equals() finalize() getclass() hashcode() notify() notifyall() Object() tostring() wait() wait(long timeout) wait(long timeout, int nanos) java.lang.string java.awt.event.windowadapter java.util.eventobject java.awt.awtevent java.awt.component java.awt.windowevent java.awt.container java.awt.componentevent java.awt.swing.jpanel java.awt.swing.jlabel java.awt.window java.awt.frame java.awt.swing.jframe Abstraction Fig. 1.1 Inheritance Abstraction can be defined as the process in which an application will ignore the characteristics of a sub-group and work on a general level when it is needed. As an example, Betsy the cat may be treated as a cat when it is necessary, but it can also be processed as a Felidae, which is a superclass of cat family. Polymorphism Polymorphism can be defined as a behaviour which is dependent on the class to which it is connected. As an example, if a Cat is sent a command to speak, this may cause it to purr, while a dog will bark, or a lion may roar. 4

15 Encapsulation Encapsulation will allow a class to hide information from objects that may use the code. For example, the Cat class will have a purr () method. A code will be written which will explain how the cat purrs. Despite this, it is not necessary for Betsy the cat to know how she purrs Encapsulation makes it easier for the developer to change the code without having to change the code for Betsy. When the structure of class is hidden, it is harder for it to be used in the wrong way. Encapsulation will basically state which class is allowed to use the members of a certain object. This concept makes it easier for programmers to deal with or avoid errors when developing a program. The members within OOP can be categorized as being protected, public, or private. Event An event can simply be defined as anything that happens to an object. Generally, an event is something that will cause the object to react with a method. Another term that advanced programmers may run into is called multiple inheritance. It is a situation where a class is able to inherit traits from a number of different superclasses. A multiple inheritance can create a number of perplexing situations. Because of this, there is debate in the programming community about whether it is beneficial or risky. One example of a program which deals with multiple inheritances is Java. It will permit a class to have interfaces which come from multiple parents, but it can only inherit methods from a single parent. Other programming languages which use this approach are C# and Visual Basic. There are a number of popular object oriented programming languages that are being used, and one of the most popular is Java. 1.3 Object Oriented Programming Object-orientation is a set of tools and methods that enable software engineers to build reliable, user friendly, and maintainable, well documented, reusable software systems that fulfils the requirements of its users. It is claimed that object-orientation provides software developers with new mind tools to use in solving a wide variety of problems. Object-orientation provides a new view of computation. A software system is seen as a community of objects that cooperate with each other by passing messages in solving a problem. An object-oriented programming language provides support for the following object-oriented concepts: Objects and Classes Inheritance Polymorphism Dynamic binding 1.4 Programming Paradigm Object-oriented programming is one of several programming paradigms. Other programming paradigms include the imperative programming paradigm (as exemplified by languages such as Pascal or C), the logic programming paradigm (Prolog), and the functional programming paradigm (exemplified by languages such as ML, Haskell or Lisp). Logic and functional languages are said to be declarative languages. We use the word paradigm to mean any example or model. This usage of the word was popularised by the science historian Thomas Kuhn. He used the term to describe a set of theories, standards and methods that together represent a way of organising knowledge a way of viewing the world. Thus a programming paradigm is a 5

16 Object Oriented Programming through Java... Way of conceptualising what it means to perform computation and how tasks to be carried out on a computer should be structured and organised. We can distinguish between two types of programming languages: Imperative languages Declarative languages Imperative language Imperative knowledge describes how-to knowledge Traditional imperative programming languages such as FORTRAN, and C, which require the programmer to specify an algorithm to be run Imperative programs make the algorithm explicit and leave the goal implicit Imperative languages requires to write down a stepby-step recipe specifying how something is to be done Declarative language Declarative knowledge is what-is knowledge Declarative program describes what something is like, rather than how to create it Declarative programs make the goal explicit and leave the algorithm implicit For example: to calculate the factorial function in an imperative language we would write something like public int factorial(int n) int ans=1; for (int i = 2; i <= n; i++) ans = ans * i; return ans; Given above is a procedure (a set of steps) when followed will produce the answer. 1.5 Functional Programming Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions. Functional programming emphasizes the definition of functions, in contrast to procedural programming, which emphasizes the execution of sequential commands. The following is the factorial function written in a functional language called Lisp: ( defun factorial (n) (if (<= n 1) 1 (* n (factorial (- n 1)))) ) It defines the factorial function rather than give the steps to calculate it. The factorial of n is defined as 1 if n <= 1 else it is n factorial (n 1) 6

17 1.6 Logic Programming Prolog (PROgramming in LOGic) is the most widely available language in the logic programming paradigm. It is based on the mathematical ideas of relations and logical inference. Prolog is a declarative language meaning that rather than describing how to compute a solution, a program consists of a data base of facts and logical relationships (rules) which describe the relationships which hold for the given application. Rather then running a program to obtain a solution, the user asks a question. When asked a question, the run time system searches through the data base of facts and rules to determine (by logical deduction) the answer. Logic programming was an attempt to make a programming language that enabled the expression of logic instead of carefully specified instructions on the computer. In the logic programming language Prolog supplies a database of facts and rules; we can then perform queries on the database. This is also an example of a declarative style of programming where we state or define what we know. In the following example, we declare facts about a domain. We can then query these facts we can ask, for example, are sally and tom siblings? sibling(x,y) : parent(z,x), parent(z,y). parent(x,y) : father(x,y). parent(x,y) : mother(x,y). mother(trude, sally). father(tom, sally). father(tom, erica). father(mike, tom). The factorial function is written in prolog as two rules. Again, notice the declarative nature of the program fac(0,1). fac(n,f) : N > 0. M is N 1, fac(m, Fm), F is N * Fm. 1.7 Object Orientation as a New Paradigm: The Big Picture It is claimed that the problem-solving techniques used in object-oriented programming more closely models the way humans solve day-to-day problems. So let s consider how we solve an everyday problem: For example: Suppose we want to send flowers to a friend named Robin who lives in another city. To solve this problem, we will simply walk to our nearest florist run by, let s say, Fred. We will tell Fred the kinds of flowers to be sent and the address to which they should be delivered. We will be assured that the flowers will be delivered. Now, let s examine the mechanisms used to solve our problem. We first found an appropriate agent (Fred, in this case) and passed a message to this agent containing a request. It is the responsibility of Fred to satisfy the request. There is a method (an algorithm or set of operations) used by Fred to do this. We need not know the particular methods used to satisfy the request such, information are hidden from view. We want to know the details, but on investigation we may find that Fred delivered a slightly different message to another florist in the city where Robin lives. That florist then passes another message to a subordinate who makes the floral arrangement. The flowers, along with yet another message, are passed onto a delivery person and so on. The florists also have interactions with wholesalers who, in turn, had interactions with flower growers and so on. 7

18 Object Oriented Programming through Java This leads to our first conceptual picture of object-oriented programming: An object-oriented program is structured as community of interacting agents called objects. Each object has a role to play. Each object provides a service or performs an action that is used by other members of the community. 1.8 Messages and Responsibilities Members of an object-oriented community make requests to each other. The next important principle explains the use of messages to initiate action. Action is initiated in object-oriented programming by the transmission of a message to an agent (an object) responsible for the actions. The message encodes the request for an action and is accompanied by any additional information (arguments/ parameters) needed to carry out the request. The receiver is the object to whom the message is sent. If the receiver accepts the message, it accepts responsibility to carry out the indicated action. In response to a message, the receiver will perform some method to satisfy the request. There are some important issues pointed below: The client sending the request need not know the means by which the request is carried out. In this we see the principle of information hiding. Another principle implicit in message passing is the idea of finding someone else to do the work, i.e., reusing components that may have been written by someone else. The interpretation of the message is determined by the receiver and can vary with different receivers. For example, if we sent the message deliver flowers to a friend, she will probably have understood what was required and flowers would still have been delivered but the method she used would have been very different from that used by the florist. In object-oriented programming, behaviour is described in terms of responsibilities. Client s requests for actions only indicate the desired outcome. The receivers are free to pursue any technique that achieves the desired outcomes. Thinking in this way allows greater independence between objects. Thus, objects have responsibilities that they are willing to fulfill on request. The collection of responsibilities associated with an object is often called a protocol. 1.9 Classes and Instances All objects are instances of a class. The method invoked by an object in response to a message is determined by the class of the receiver. All objects of a given class use the same method in response to similar messages. Fred is an instance of a category or class of people, i.e., Fred is an instance of a class of florists. The term florist represents a class or category of all florists. Fred is an object or instance of a class. We interact with instances of a class but the class determines the behaviour of instances. We can tell a lot about how Fred will behave by understanding how Florists behave. We know, for example, that Fred, like all florists can arrange and deliver flowers. Real-world objects share two characteristics. They all have state and behaviour. For example, dogs have state (name, colour, breed, and hungry) and behaviour (barking, fetching, wagging tail). Students have state (name, student number, courses they are registered for, gender) and behaviour (takes tests, attend courses, write tests, party). 8

19 Methods (behavior) Variables (state) Fig. 1.2 Objects Fundamentals of objects and classes We move now from the conceptual picture of objects and classes to a discussion of software classes and objects. Objects are closely related to classes. A class can contain variables and methods Objects and Classes Objects In object-oriented programming we create software objects that model real world objects. Software objects are modelled after real-world objects in that they too have state and behaviour. A software object maintains its state in one or more variables. A variable is an item of data named by an identifier. A software object implements its behaviour with methods. A method is a function associated with an object. Definition: An object is a software bundle of variables and related methods. An object is also known as an instance. An instance refers to a particular object. For example, Karuna s bicycle is an instance of a bicycle it refers to a particular bicycle. Sandile Zuma is an instance of a Student. The variables of an object are formally known as instance variables because they contain the state for a particular object or instance. In a running program, there may be many instances of an object. For example, there may be many Student objects. Each of these objects will have their own instance variables and each object may have different values stored in their instance variables. For example, each Student object will have a different number stored in its StudentNumber variable Encapsulation Object diagrams show that an object s variables make up the center, or nucleus, of the object. Methods surround and hide the object s nucleus from other objects in the program. Packaging an object s variables within the protective custody of its methods is called encapsulation. 9

20 Object Oriented Programming through Java Message Object A Object B Fig. 1.3 Messages Encapsulating related variables and methods into a neat software bundle is a simple yet powerful idea that provides two benefits to software developers: Modularity The source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system. We can give our bicycle to someone else, and it will still work. Information-hiding An object has a public interface that other objects can use to communicate with it. The object can maintain private information and methods that can be changed at any time without affecting other objects that depend on it Messages Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B s methods, object A sends a message to object B. For example: The three parts for the message System.out.println Hello World ; are: The object to which the message is addressed (System.out) The name of the method to perform (println) Any parameters needed by the method ( Hello World! ) Classes In object-oriented software, it s possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips and so on. A class is a software blueprint for objects. A class is used to manufacture or create objects. The class declares the instance variables necessary to contain the state of every object. The class would also declare and provide implementations for the instance methods necessary to operate on the state of the object. Definition: A class is a blueprint that defines the variables and the methods common to all objects of a certain kind. 10

21 After we create the class, we can create any number of objects from that class. A class is a kind of factory for constructing objects. The non-static parts of the class specify, or describe, what variables and methods the objects will contain. This is a part of the explanation of how objects differ from classes: Objects are created and destroyed as the program runs, and there can be many objects with the same structure, if they are created using the same class. A class is a structure that defines the data and the methods to work on that data. When we write programs in the Java language, all program data is wrapped in a class, whether it is a class we write or a class we use from the Java platform API libraries. The ExampleProgram class from the simple program in the first lesson of Part 1 is a programmer-written class that uses the java.lang.system class from the Java platform API libraries to print a character string to the command line. class ExampleProgram public static void main(string[] args) System.out.println( I m a simple Program ); Classes in the Java platform API libraries define a set of objects that share a common structure and behaviour. The java.lang.system class used in the example defines such things as standard input, output, and error streams, and access to system properties. In contrast, the java.lang.string class defines character strings. In the example, we do not see an explicit use of the String class, but in the Java language, a character string can be used anywhere a method expects to receive a String object. During execution, the Java platform creates a String object from the character string passed to the System.out.println call, but our program cannot call any of the String class methods because it did not instantiate the String object. If we want access to the String methods, we can rewrite the example program to create a String object as follows. This way, we can call a method such as the String.concat method that adds text to the original string as shown below: class ExampleProgram public static void main(string[] args) String text = new String( I m a simple Program ); System.out.ptringln(text); String text2 = text.concat( that uses classes and objects ); System.out.println(text2); The output looks like this: I m a simple Program I m a simple Program that uses classes and objects 11

22 Object Oriented Programming through Java 1.12 Types Java, like most programming languages classifies values and expressions into types. For example, String s and int s are types. A type basically specifies the allowed values and allowed operations on values of that type. Definition: A type is a set of values together with one or more operations that can be applied uniformly to all these values. A type system basically gives meaning to collections of bits. Because any value simply consists of a set of bits in a computer, the hardware makes no distinction between memory addresses, instruction code, characters, integers and floating-point numbers. Types inform programs and programmers how they should treat those bits. For example, the integers are a type with values in the range 2, 147, 483, 648 to +2, 147, 483, 647 and various allowed operations that include addition, subtraction, modulus etc. The use of types by a programming language has several advantages like: A. Safety Use of types may allow a compiler to detect meaningless or invalid code. For example, we can identify an expression Hello, World / 3 as invalid because one cannot divide a string literal by an integer. Strong typing offers more safety. B. Optimisation Static type-checking may provide useful information to a compiler. The compiler may then be able to generate more efficient code. C. Documentation Types can serve as a form of documentation, since they can illustrate the intent of the programmer. For instance, timestamps may be a subtype of integers but if a programmer declares a method as returning a timestamp rather than merely an integer, this documents part of the meaning of the method. D. Abstraction Types allow programmers to think about programs at a higher level, not bothering with low-level implementation. For example, programmers can think of strings as values instead of as a mere array of bytes. There are fundamentally two types in JAVA: primitive types and objects types, i.e., any variable we declare are either declared to be one of the primitive types or an object type. int, double and char are the built-in, primitive types in JAVA. The primitive types can be used in various combinations to create other, composite types. Every time we define a class, we are actually defining a new type. For example, the Student class defined above introduces a new type. We can now use this type like any other type: we can declare variables to be of this type and we can use it as a type for parameters of methods. Before a variable can be used, it must be declared. A declaration gives a variable a name, a type and an initial value for e.g. int x = 8 declares x to be of type int. All objects that we declare also have to be of a specified type the type of an object is the class from which it is created. 12

23 Thus, when we declare objects we state the type like so: Student st = newstudent();. This statement declares the variable st to be of type Student. This statement creates a new object of the specified type and runs the Student constructor. The constructor s job is to properly initialise the object. The String type is another example of an object type. Student and String are composite types and give us the same advantages as the built-in types. The ability to create our own types is a very powerful idea in modern languages. When declaring variables, we can assign initial values. If we do not specify initial values, the compiler automatically assigns one: Instance variables of numerical type (int, double, etc.) are automatically initialized to zero; Boolean variables are initialized to false; and char variables, to the Unicode character with code number zero. The default initial value of object types is null. 13

24 Object Oriented Programming through Java Summary Object Oriented Programming, also known as OOP, is a computer science term which is used to describe a computer application that is composed of multiple objects which are connected to each other. Traditionally, most computer programming languages were simply a group of functions or instructions. With OOP, every object can handle data, get messages, and transfer messages to other objects. Three of the most basic concepts for object oriented programmings are Classes, Objects, and Methods. Inheritance will allow a sub-group to make a connection with the associates of its parent class. For example, lets say the class Cats decides to create a method called purr() and a property named Colorfur. As the name implies, a property is a specific attribute which is connected to an object. Abstraction can be defined as the process in which an application will ignore the characteristics of a sub-group and work on a general level when it is needed. Encapsulation will allow a class to hide information from objects that may use the code. Polymorphism can be defined as a behaviour which is dependent on the class to which it is connected An event can simply be defined as anything that happens to an object. A multiple inheritance can create a number of perplexing situations. Because of this, there is debate in the programming community about whether it is beneficial or risky. Object-orientation is a set of tools and methods that enable software engineers to build reliable, user friendly, and maintainable, well documented, reusable software systems that fulfils the requirements of its users. It is claimed that object-orientation provides software developers with new mind tools to use in solving a wide variety of problems. An object-oriented programming language provides support for the following object-oriented concepts: objects and classes, inheritance, polymorphism, and dynamic binding Along with the object-oriented programming the other paradigms include the imperative programming paradigm (as exemplified by languages such as Pascal or C), the logic programming paradigm (Prolog), and the functional programming paradigm (exemplified by languages such as ML, Haskell or Lisp). References C. Thomas Wu, An Introduction to Object-Oriented Programming with Java. McGraw-Hill Higher Education. Mulholland, A. and Murphy, G., Java 1.4 Game Programming. Wordware Publishing. Wu, T., An Into To Oop with Java, 4E. Tata McGraw-Hill. Recommended Reading Horstmann, C. S. and Cornell, G., Core Java 2: Fundamentals. Prentice Hall PTR. Anderson, J. and Franceschi, H., Java 6 illuminated: an active learning approach. Jones & Bartlett Learning. Barnes, D. J., Object-oriented programming with Java: an introduction. Prentice Hall. 14

25 Self Assessment 1. What is the full form of OOP? a. Object Organisation Process b. Object Orbit Pro c. Object Oriented Programming d. Object Organic Programme With OOP, every object can handle data, get messages, and transfer messages to other. a. objects b. c. d. program process subroutine can be defined as a specific instance of a class. a. Object b. c. d. Program Class Method Every object within an language will share some attributes with parent class, but it will also have unique attributes as well. a. C++ b. c. d. OOP C Java A method may also be called a. a. code b. c. d. memo communication message A is a method that is composed of a part within an object. a. call-back b. c. d. call-rear call in send out Three of the most basic concepts for are classes, objects, and methods. a. coding b. c. d. programming object oriented programming s java 15

26 Object Oriented Programming through Java Object-oriented concept that helps objects work together is. a. inheritance b. heritage c. enhancement d. hashing Inheritance defines relationships among in an object-oriented language. a. diagrams b. methods c. classes d. object s 10. can be defined as the process in which an application will ignore the characteristics of a sub-group and work on a general level when it is needed. a. Inheritance b. c. d. Methods Classes Abstraction 16

27 Chapter II Classes, Objects and Methods Aim The aim of this chapter is to: introduce the concept of class objects, class and methods explain field declaration elaborate the concept of class Objectives The objectives of this chapter are to: introduce methods declaration explain the method of creating objects discuss how to create object references Learning outcome At the end of this chapter, you will be able to: understand the applications of classes and objects describe the concept of constructors and its application access the class members 17

28 Object Oriented Programming through Java 2.1 Introduction Java is a true object oriented language and therefore, the underlying structure of all Java programs is classes. Anything we wish to represent in a Java program must be encapsulated in a class that defines the state and behaviour of the basic program components known as objects. Classes create objects and objects use methods to communicate between them. Classes provide a convenient method for packing together a group of logically related data items and functions that work on them. In Java, the data items are called are called fields and the functions are called methods. Calling a specific method in an object is described as sending the object a message. A class is essentially a description of how to make an object that contains fields and methods. It provides a sort of template for an object and behaves like a basic data type int. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build Java program that incorporates the basic OOP concepts such as encapsulation, inheritance and polymorphism. 2.2 Defining a Class A class is a user-defined data type with a template that serves to define its properties. Once the class type has been defined, we create variable of that type using declaration that are similar to the basic type declaration. In Java, these variables are termed as instances of classes, which are the actual objects. The basic form of a class definition is: Class classname [extends superclassname] [ fields declaration; ] [ methods declaration: ] Everything inside the square brackets is optional. This means that the following would be a valid class definition. Class Empty Because the body is empty, this class does not contain any properties and therefore cannot do anything. We can, however, compile it and even create objects using it. C++ programmers may note that there is no semicolon after closing brace. Classname and superclassname are any valid Java identifiers. The keywords extends indicates that the properties of the superclassname class are extended to the classname class. 2.3 Fields Declaration Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables because they are created whenever an object of the class is instantiated. We can declare the instance variables exactly the same way as we declare local variables. For example: class Rectangle int length; int width; 18

29 The class rectangle contains two integer type instance variables. It is allowed to declare them in one line as int length, width; Remember these variables are only declared and therefore no storage space has been created in the memory. Instance variables are also known as member variables. 2.4 Methods Declaration A class with only data fields (and without methods that operate on that data) has no life. The objects created by such a class cannot respond to any messages. We must therefore add methods that are necessary for manipulating the data contained in the class. Methods are declared inside the body of the class but immediately after the declaration of instance variables. The general form of a method declaration is: Method declarations have four basic parts: The name of the method (methodname) type methodname (parameter-list) Method-body The type of the value the method returns (type) A list of parameters (parameter-list) The body of the method The type specifies the type of value the method would return. This could be simple data type such as int as well as any class type. It could even be void type, if the method does not return any value. The methodname is a valid identifier. The parameter list is always enclosed in parentheses. This just contains variable names and types of all the values we want to give to the method as input. The variables in the list are separated by commas. In the case, where no input data are required, the declaration must retain the empty parentheses. Examples: (int m. float x. float y) // Three parameters ( ) // Empty list The body actually describes the operations to be performed on the data. Let us consider the Rectangle class again and add a method getdata ( ) to it. class Rectangle int length; int width; void getdata (int x, int y) // Method declaration length = x; width = y; 19

30 Object Oriented Programming through Java Note that the method has a return type of void because it does not return nay value. We pass two integer values to the method which are then assigned to the instance variables length and width. The getdata method is basically added to provide values to the instance variables. Notice that we are able to use directly length and width inside the method. Let us add some more properties to the class. Assume that we want to compute the area of the rectangle defined by the class. This can be done as follows: class Rectangle int length, width; // Combined declaration void getdata (int x. int y) length = x; width = y; int rectarea ( ) // Declaration of another method int area = length * width; return (area); The new method rectarea( ) computes area of the rectangle and returns the result. Since the result would be an integer, the return type of the method has been specified as int. Also note that the parameter list is empty. Remember that while the declaration of instance variables (and also local variables) can be combined as int length, width; the parameter list used in the method header should always be declared independently separated by commas. That is, is illegal. void getdata (int x, y) // Incorrect Now, our class Rectangle contains two instance variables and two methods. We can add more variables and methods, if necessary. Most of the times when we use classes, we have many methods and variables within the class. Instance variables and methods in classes are accessible by all the methods in the class but a method cannot access the variables declared in other methods. 20

31 For example: class Access int x; void method1 ( ) int y ; x = 10; y = x; Void method 2 ( ) Int z; X = 5 Z = 10 ; // legal Y = 1 ; // legal // legal // legal // illegal 2.5 Creating Objects An object in Java is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object. Objects in Java are created using the new operator. The new operator creates an object of the specified class and returns a reference to that object. Here is an example of creating an object of type Rectangle. Rectangle rect1; rect1 = new Rectangle ( ); // declare the object // instantiate the object The first statement declares a variable to hold the object reference and the second one actually assigns the object reference to the variable. The variable rect1 is now an object of the Rectangle class. Action Statement Result Declare Rectangle rect1; null rect1 Instantiate rect1 = new Rectangle ( ) rect1 rect1 is a reference to Rectangle object Rectangle Object Fig. 2.1 Creating object references Both statements can be combined into one as shown below: Rectangle rect1 = new Rectangle ( ); The method Rectangle ( ) is the default constructor of the class. We can create any number of objects of Rectangle. Example: Rectangle rect1 = new Rectangle ( ); Rectangle rect2 = new Rectangle ( ); and so on. 21

32 Object Oriented Programming through Java It is important to understand that each object has a its own copy of the instance variables of its class. This means that any changes to the variables of one object have no effect on the variables of another. It is also possible to create two or more references to the same object. Rectangle R1 = new Rectangle (); Rectangle R2 = R1; R1 Rectangle Object R1 Both, R1 and R2 refer to the same object. 2.6 Accessing Class Members Fig. 2.2 Assigning one object reference variable to another Now that we have created objects, each containing its own set of variables, we should assign values to these variables in order to use them in our program. Remember, all variables must be assigned values before they are used. Since we are outside the class, we cannot access the instance variables and the methods directly. To do this, we must use the concerned object and the dot operator as shown below: Objectname.variablename = value; Objectname.methodname (parameter-list); Here, objectname is the name of the object; variablename is the name of the instance variable inside the object that we wish to access, methodname is the method that we wish to call, and parameter-list is a comma separated list of actual values (or expressions) that must match in type and number with the parameter list of the methodname declared in the class. The instance variables of the Rectangle class may be accessed and assigned values as follows: rect1.length = 15; rect1.width = 10; rect2.length = 20 rect2.width = 12; Note that the two objects rect1 and rect2 store different values as shown below: rec1 rec2 rect1.length 15 rect2.length 20 rect1.width 10 rect2.width 12 22

33 This is one way of assigning values to the variables in the objects. Another way and more convenient way of assigning to the instance variables is to use a method that is inside the class. In our case, the method getdata can be used to do this work. We can call the getdata method on any Rectangle object to set the values of both length and width. Here is the code segment to achieve this. Rectangle rect1 = new rectangle ( ); // Creating an object Rect1.getData (15, 10); // Calling the method using the object This code creates rect1 object and then passes in the values 15 and 10 for the x and y parameters of the method getdata. This method then assigns these values to length and width variables respectively. For the sake of convenience, the method is again shown below: void getdata (int x, inty) length = x; width = y; Now that the object rect1 contains values for its variables, we can compute the area of the rectangle represented by rect1. This again can be done in two ways. The first approach is to access the instance variables using the dot operator and compute the area. That is. int area1 = rect1.length * rect1.width; The second approach is to call the method rectarea declared inside the class. That is, int area1 = rect1.rectarea ( ); // calling the method Program 2.1 below illustrates the concepts discussed above. Program 2.1 Application of classes and objects 23

34 Object Oriented Programming through Java class Rectangle int length.width; // Declaration of variables void getdata (intx, inty) // Definition of method length = x; width = y; int rectarea ( ) // Definition of another method int area = length*width; return (area); class RectArea // Class with main method Public static void main (String args [ ] ) int area1.area2; Rectangle rect1 = new Rectangle ( ); // Creating objects Rectangle rect2 = new Rectangle ( ); Rect1.length = 15; // Accessing variables rect1.width = 10; area1 = rect1.length * rect1.width; rect2.getdata (20, 12) // Accessing methods area2 = rect2.rectarea ( ); System.out.println ( Area1 = + area1); System.out.println ( Area12= + area2); Program 2.1 would output the following Area1 = 150 Area2 = Constructors We know that all objects are created must be given initial values. We have done this earlier using two approaches. This first approach uses the dot operator to access the instance variables and then assigns values to them individually. It can be tedious approach to initialize all the variables of all the objects. The second approach takes the help of a method like getdata to initialize each object individually using statements like, rect1.getdata (15, 10); It would be simpler and more concise to initialise an object when it is created. Java supports a special type of method, called a constructor that enables an object to initialize itself when it is created. Constructors have the same name as the class itself. Secondly, they do not specify a return type, not even a void. This is because they return the instance of the class itself. Let us consider our Rectangle class again. We can now replace the getdata method by a constructor method as shown below: 24

35 class Rectangle int length; int width; Rectangle (int x, int y) // Constructor method length = x; width = y; int rectarea ( ) return (length*width); Program 2.2 below illustrates the use of constructor method to initialise an object at the time of its creation. Program 2.2 Application of constructors class Rectangle int length, width; Rectangle ( int x, int y) length = x; width = y; int rectarea ( ) return (length * width); class RectangleArea public static void main (string args[ ] ) Output of program 2.2: Area1 = 150 Rectangle rect1 = new Rectangle (15, 10); int area1 = rect1.area ( ); System.out.println ( Area1 = + area1); // Defining constructor // Calling constructor 25

36 Object Oriented Programming through Java Summary Java is a true object oriented language and therefore the underlying structure of all Java programs is classes In Java, the data items are called are called fields and the functions are called methods Anything we wish to represent in a Java program must be encapsulated in a class that defines the state and behaviour of the basic program components known as objects A class is a user-defined data type with a template that serves to define its properties. Once the class type has been defined, we create variable of that type using declaration that are similar to the basic type declaration Classname and superclassname are any valid Java identifiers Data is encapsulated in a class by placing data fields inside the body of the class definition. These variables are called instance variables because they are created whenever an object of the class is instantiated Methods are declared inside the body of the class but immediately after the declaration of instance variables Method declarations have four basic parts: the name of the method (methodname), the type of the value the method returns (type), a list of parameters (parameter-list), and the body of the method An object in Java is essentially a block of memory that contains space to store all the instance variables. Creating an object is also referred to as instantiating an object. Objects in Java are created using the new operator. The new operator creates an object of the specified class and returns a reference to that object Java supports a special type of method, called a constructor that enables an object to initialise itself when it is created. References Classes and Objects in Java, [online]. Available at: < CIQFjAB&url=http%3A%2F%2Fwww.buyya.com%2F254%2FLectures%2FRajLec7.ppt&rct=j&q=classes%20 and%20objects%20in%20java&ei=tsartfehl4n0vqpw5pt_cq&usg=afqjcnetrpuizb_l_kpicbpldakld 23Rfw&sig2=R9TRHATEAa2rWQ29N3a6vg&cad=rja>. [Accessed 8 April 2011] Classes and Objects in Java, [online]. Available at: < [Accessed 8 April 2011] Javabeginner.com, 2008, Java Classes and Objects, [online]. Available at: < learn-java/java-classes-and-objects>. [Accessed 8 April 2011] Recommended Reading Sierra, K., Head First Java. 2 nd ed., O Reilly Media Barnes, D.J. & Kolling, M., Objects First With Java: A Practical Introduction Using BlueJ. 4 th ed., Prentice Hall Bronson, G. J., Object-Oriented Program Development Using Java: A Class-Centered Approach. 2 nd ed., Course Technology 26

37 Self Assessment 1. Underlying structure of all Java programs is. a. methods b. classes c. objects d. instances An object in Java is essentially a block of memory that contains space to store all the: a. Instance variables b. Object variables c. Basic variable d. Dot variable Which of the following statements is false? a. Calling a specific method in an object in an object is described as sending the object a message. b. A class is essentially a description of how to make an object that contains fields and methods c. Classes provide a difficult method for packing together a group of logically related data items and functions that work on them d. Classes create objects and objects use methods to communicate between them. Objects in Java are created using the. a. new operator b. data operator c. object operator d. class operator Data is in a class by placing data fields inside the body of the class definition. a. communicated b. provided c. packed d. encapsulated Constructors have the same name as the: a. object itself b. method itself c. class itself d. instance itself Which of the following statement is true? a. A class is a user-defined object type with a template that serves to define its properties b. We can declare the instance variables exactly the same way as we declare global variables. c. Creating an object is also referred to as instantiating an object d. It is important to understand that each object has a its own copy of the instance variables of its object 27

38 Object Oriented Programming through Java Java supports a special type of method, called a that enables an object to initialise itself when it is created. a. constructor b. c. d. destructor method message Calling a specific method in an object is described as sending the object a. a. message b. c. d. communication data object 10. Classname and superclassname are any valid identifiers. a. object b. class c. method d. java 28

39 Chapter III Inheritance Aim The aim of this chapter is to: introduce the concept of inheritance explain the effects of inheritance identify the overriding methods Objectives The objectives of this chapter are to: introduce protected access explain the dynamic method dispatching discuss the concept of interfaces derive the syntax of inheritance Learning outcome At the end of this chapter, you will be able to: understand the concept of super keyword and constructor chaining describe abstract classes access the casting between class type identify the final methods and final classes 29

40 Object Oriented Programming through Java 3.1 Introduction to Inheritance Inheritance is a powerful feature that allows new classes to be derived from existing ones. The derived class inherits the interface of the base class and can add new methods or change existing ones to suit its purpose. Any number of classes can be added to an inheritance scheme to produce a hierarchy of related types. The Java implementation of inheritance supports polymorphism, which allows objects of different types to be treated as if they were of the same type. Developers working with object-oriented languages visualise classes as being related to each other in hierarchies of kind of relationships. Just as programmers generalise the common features of objects in an abstract data type, they also identify and abstract common features of similar types in a superclass. Once the superclass is defined, each subclass is defined as a kind of the superclass, so that it can then inherit the common features. The programmer need only specify the behaviour that sets the subclass apart from its parent and its siblings. Java programmers say that the subclasses are derived from the superclass, and refer to them as derived types and base types, respectively. Programmers conceptualise programs both, upward and downward, through levels of abstraction during the design and implementation stages of a development cycle. However, it is observed that they usually tend to think predominantly from the bottom up during the design phase, and predominantly top down during the implementation phase. Once the characteristics of a superclass are well described, its interface can be written before the subclasses are developed. Each subclass inherits both its superclass s interface and its implementation. It modifies and extends the former, or extends only the latter, as needed. The use of inheritance produces a hierarchy of classes Example of Inheritance An example of inheritance where a programmer might identify a need for two types of text objects would be CompactText and WordProcText. CompactText emphasises storage efficiency rather than functionality and WordProcText is used for word processing that contains font information. While the differences between the text objects are significant enough to warrant implementing them as different classes, the similarities that exist between them suggest the presence of certain shared properties and the possibility of their belonging to one superclass. In this case, rather than creating two largely similar class definitions, a superclass called TextObject can be first defined. This establishes a common interface for the two. From this base class, the classes CompactText and WordProcText are derived. Each derived type inherits its interface and implementation from the base type. For example, all of the classes have a length( ) method. The base class might or might not provide a default implementation for this method. If the base class does provide a default implementation, the derived classes can inherit the implementation as their own. A derived class can override or extend the implementation of an inherited method as appropriate. A derived class may not change the interface of a method. CompactText might use the implementation of the length( ) method defined in TextObject, while WordProcText might override this implementation with its own. Perhaps, it is only later that an EncodedText type is needed. If an inheritance relationship exists, then implementing the new type becomes much simpler. Whether or not derived classes are created at the same time as their base class, each of the derived types extends the interface or implementation of the base class. Establishing a sensible hierarchy of related types is one of the most challenging aspects of object-oriented program design. It is not easy to generalise a base type in a manner that not only abstracts the common behavior of the types already known, but also provides a good basis for the later derivation of new types. An important reward for utilising inheritance is a dramatic increase in code reuse, which can save a programmer time and valuable resources. 30

41 3.1.2 Derivation Syntax The keyword extends in the subclass definition below declares one class as a subclass of another. A Java class may derive from at most one base class. public class TextObject public int length ()... public class CompactText extends TextObject public class WordProcText extends TextObject Any user-defined class that does not explicitly derive from another class derives from the library class java.lang. Object. The Object class is therefore the ultimate base class of all other Java classes. The Object class provides the equals( ) method as well as other features common to all Java objects Effects of Inheritance In Java, private methods of the base class are not inherited (the derived class cannot call them anyway), but everything else is inherited. A derived-type object can be said to have a dual identity. It is a type of both its new class and its parent type. For example, if class Bass is derived from Fish, an object of type Bass is both a Bass and a Fish. However, the reverse is not necessarily true. The programmer, in this case, must force a conversion from base class type to derived class type with an explicit cast: 3.2 Protected Access BaseClass Obj1; /*...*/ DerivedClass Obj2=(DerivedClass) Obj1; In addition to public, private and default (package-friendly) member access, there are two other access specifiers that apply only to derived classes. Any member that is declared protected is accessible only by a class that is derived from the current class or is in the same package as the containing class. Any member that is declared private protected is accessible only by a class that is derived from the containing class. Consider the following example: public class A protected int x; private protected int y; Member x is accessible to any class that derives from class A and to any class in the same package as class A. Member y is only accessible to any class that derives from class A. 31

42 Object Oriented Programming through Java Fig. 3.1 below shows the relationship between classes with different access specifiers. Package Stuff Package Things Class A Class E Class C (derived) Class B Class D Fig. 3.1 Accessibility in an inheritance relationship Access specifier Public Protected Default Private protected private A, B, C, D, E A, B, C, D A, B, C A, B, D A Accessible by classes 3.3 Overriding Methods Table 3.1 Access to class A s members The process of a derived class redefining a method contained in the parent class (with the same parameter types) is called overriding the method. Whenever a method is called for a derived-type object, the compiler calls the overriding version instead of the inherited version. The method is thus implemented in a way that is unique to the derived class. The following is a syntax example: public class TextObject public int length () // TextObject s implementation public class CompactText extends TextObject public int length () // CompactText s implementation This allows a programmer to use a parent type variable to point to a derived type object, call a method for that object, and have the compiler call the specialised version. This is how polymorphism is implemented. C++ programmers will recognise this as a virtual function. In Java, all methods are virtual unless specified otherwise. 32

43 3.3.1 Dynamic Method Dispatching Consider the following example: class Fish void eat(), other items... class Bass extends Fish void eat()... class Shark extends Fish void eat()... Fish redfish, bluefish; redfish = new Bass(); bluefish = new Shark(); redfish.eat(); bluefish.eat(); The compiler cannot tell at compile-time which method to call here. The solution entails waiting until run-time to determine which function is the correct one. In other words, the run-time code must check the actual type rather than the apparent type of an object based on the name of the variable used in the code. This is known as dynamic method dispatching The Super Keyword It is often desirable for an overriding implementation of a method to call the inherited implementation of the method. Often, the inherited code need not be completely replaced, only augmented to add some new actions. Any method in a derived class that overrides a method in the base class can call the corresponding base class method by using the super keyword as shown below: public class WordProcText extends TextObject public int length () int len = super.length ();... return len; Note that there is no way to access a method overridden more than once. The following code is illegal: super.super.f() Final Methods and Final Classes Dynamic lookup takes time. Therefore, there are some situations where it should be disabled. Also, there are some methods for which the compiler must be able to resolve a required action, or for which an overriding version would be too complicated to implement. Methods labeled final, private, or static are not subject to dynamic lookup because they may not be overridden. Private methods are simply not inherited because they would never be callable anyway. Static methods apply to a particular class s static data and thus make no sense in a derivation. Final methods are those designated as notoverrideable for reasons of complexity or safety 33

44 Object Oriented Programming through Java 3.4 Constructor Chaining When a derived-type object is instantiated, it is sometimes desirable to have its constructor call a particular overload of its parent class. This is done with what looks like a call to the method super( ). Often this is used to pass a particular variable up into a parent class s constructor. This must be the first statement in a constructor. If the programmer does not include a super( ) call, the compiler will provide one. The only exception to this occurs when a constructor calls another constructor via the form this( ). In this case, the compiler knows that the first constructor will call super( ). Constructors do not use dynamic lookup simply because each class has its own constructor. Consider the following two classes: public class A A(int ix)... A(float fx)...// overloaded public class B extends A B(int ix)... The keyword super can be used to specify which of A s constructors to call from B s constructor: class B extends A B(int ix) super(ix);// calls A(int ix) This use of super( ) is legal only as the first statement of a constructor. If a constructor calls neither super( ) nor this( ), the compiler implicitly calls the base class s no-parameter constructor as seen in the figure shown below. 34

45 class A A ()... A (float xx)... Compiler calls class B extends A A () here B ()... B (float fx) super (fx) ;... B (int ix) this () ; but not here... Fig. 3.2 Constructor chaining One common mistake is to define a particular constructor in a parent class, and then derive from it without calling super( ). In this case, the compiler would call the parent class s no-parameter constructor, but would not have defined one. This can produce some mystifying error messages. The appropriate overload must exist in the parent class. Recall that if any constructor is written, the compiler will not provide the default no-parameter version. The following will produce a compiler error: 3.5 Inheritance and Finalization class A int value; A(int input) value = input; class B extends A int myvalue; If a parent class contains a finalize( ) method, it must be called explicitly by the derived class s finalize( ) method. Unlike C++, Java destructors are not called automatically. If it is needed, the derived class s finalize( ) method must call it manually with: super.finalize(); 35

46 Object Oriented Programming through Java 3.6 Abstract Classes class A int value; A(int input) value = input; class B extends A int myvalue; Methods declared with the keyword abstract define a skeleton for a method but do not implement it. This requires a derived class to provide the code for this class. A class with one or more abstract methods must itself be declared abstract and cannot be instantiated. It can only be used for derivation. C++ programmers will recognise this as a pure virtual function that makes an abstract class. A method can be declared abstract with no brackets to enclose any code. abstract float area () ; class Shape (derived) Circle Square Triangle Fig. 3.3 The relationship between an abstract class and its derived classes A generic shape cannot exist. Each subtype implements its own area( ) method. 3.7 Interfaces Some languages support multiple inheritance in which a child class may derive some of its features from one parent class and other features from another (or others). There is a continuing controversy over whether the benefits promised by this feature justify the extra complexity that comes with it. Java does not support multiple inheritance. However, it does provide a mechanism called an interface whereby the properties of one class can be used by another without formal inheritance. This enables Java to avoid most of the syntactical complications that multiple inheritance requires. When a parent class is to be defined as abstract, instead of defining one or more methods as abstract, the class can be defined with the keyword interface instead of class. This defines the minimum set of methods a class must contain. An interface type is named for derivation with the keyword implements instead of extends. All of its methods are implicitly public and abstract. If desired, they can be declared that way for clarity. Also, any data defined in an interface must be constant (i.e., final static). 36

47 3.7.1 The Implements Declaration A derived class cannot have two parent classes, as multiple inheritance leads to problems of how to decide which method to use for inherited methods. Yet, multiple inheritances are desirable because it lets an object be assigned into, and thus used as, variables of different types. For example, a programmer might instantiate a Circle as a class derived from Shape, yet wish to pass it into a method requiring a Graphic object parameter. The implements declaration in fig. 3.3, seen as a way of deriving from an interface, also means that the new class can be treated as being of that new type. Though a class can have only one parent class, it can implement any number of classes, and thus behave as more than one type of object. For example: interface Shape... class Circle extends Drawable implements Shape... class Square extends Drawable implements Shape... Shape sp1 = new Circle(), sp2 = new Square(); sp1.area(); sp2.area(): The classes circle and square are derived from class drawable, but by implementing shape, they also inherit shape s interface and are enabled to act as polymorphic instances of Shape. With interface and implements, Java supports the polymorphic features of multiple inheritance, while yet avoiding the complications of methods implemented in multiple ways. 3.8 Casting between Class Types The Java run-time system keeps track of the type of each object. While this implies some memory space overhead for each object, the programmer can achieve a type-safe run-time environment. The Java language makes some of its run-time typing power available to the programmer through the instanceof operator. The form of an instanceof expression is as follows: object-expression instanceof class-name The left-hand term is any expression that evaluates to a class type. The right-hand term is the name of a class or interface. An instanceof expression returns true if the actual type of the object on the left-hand side is of the type named by the right-hand side, and false otherwise. The object is of the named type if it is of exactly the named type or is of a type that directly or indirectly extends the identified type. The instanceof operator can be use for safe casting between class types: if (tobj instanceof CompactText) CompactText ct = (CompactText) tobj; 37

48 Object Oriented Programming through Java Summary Inheritance is a powerful feature that allows new classes to be derived from existing ones. The derived class inherits the interface of the base class and can add new methods or change existing ones to suit its purpose. An example of inheritance where a programmer might identify a need for two types of text objects would be CompactText and WordProcText. CompactText emphasises storage efficiency rather than functionality and WordProcText is used for word processing that contains font information. An important reward for utilising inheritance is a dramatic increase in code reuse, which can save a programmer time and valuable resources. In Java, private methods of the base class are not inherited, but everything else is inherited. A derived-type object can be said to have a dual identity. It is a type of both its new class and its parent type. Any member that is declared protected is accessible only by a class that is derived from the current class or is in the same package as the containing class. Any member that is declared private protected is accessible only by a class that is derived from the containing class. The process of a derived class redefining a method contained in the parent class is called overriding the method. Methods declared with the keyword abstract define a skeleton for a method but do not implement it. Interface is a method whereby the properties of one class can be used by another without formal inheritance. References Balaguruswamy, E., Programming with Java - A Primer, 3/e. 7 th ed., Tata McGraw Hill publishing company limited. Lavender, G., Inheritance in Java, [online] Available at:< tutorial/java-06.pdf>. [Accessed on 11 April 2011] Javabeginner.com, 2008, Java inheritance, [online]. Available at :< java-classes-and-objects>. [Accessed 8 April 2011] Recommended Reading Horstmann, C. S. & Cornell, G., Core Java(TM), Volume I Fundamentals. 8 th ed., Prentice Hall. Shaw, P., Java inheritance FAQ (Code Style FAQ ebook series). 1 st ed.,one Percent Better. Waldo, J., Java: The Good Parts. 1 st ed., O Reilly Media. 38

49 Self Assessment 1. Any number of classes can be added to an scheme to produce a hierarchy of related types. a. inheritance b. object c. method d. keyword The Java implementation of inheritance supports, which allows objects of different types to be treated as if they were of the same type a. encapsulation b. c. d. class method polymorphism Which one of the following is the most challenging aspects of object-oriented program design? a. To use a parent type variable to point to a derived type object b. c. d. To generalise a base type Establishing a sensible hierarchy of related types To think predominantly from the bottom up during the design phase Any method in a derived class that overrides a method in the base class can call the corresponding base class method by using the keyword. a. basic b. c. d. super parent child The process of a derived class redefining a method contained in the parent class (with the same parameter types) is called. a. overriding the method b. c. d. casting between class types interface abstract classes Which of the following statements is false? a. An interface type is named for derivation with the keyword implements instead of extends b. c. d. A class with one or more abstract methods must itself be declared abstract and can be instantiated The appropriate overload must exist in the parent class. Constructors do not use dynamic lookup simply because each class has its own constructor. An important reward for utilizing inheritance is a dramatic in code reuse, which can save a programmer time and valuable resources. a. decrease b. c. d. increase breakthrough fall 39

50 Object Oriented Programming through Java is a method whereby the properties of one class can be used by another without formal inheritance. a. Casting b. Overriding c. Interface d. Chaining Which of the following statement is true? a. Methods declared with the keyword abstract define a skeleton for a method and also implement it. b. A class with one or more abstract methods must itself be declared abstract and cannot be instantiated c. An interface type is named for derivation with the keyword implements instead of declaration d. Though a class can have only two parent class, it can implement any number of classes, and thus behave as more than one type of object. 10. A derived-type object can be said to have a identity. a. single b. multiple c. optional d. dual 40

51 Chapter IV Polymorphism Aim The aim of this chapter is to: introduce the concept of polymorphism explain the method calling binding discuss the order of constructor calls Objectives The objectives of this chapter are to: explain upcasting illustrate the concept of extensibility highlight abstract classes and methods Learning outcome At the end of this chapter, you will be able to: understand the concept of constructors and polymorphism describe the differences between overriding and overloading know the program for forgetting the object type 41

52 Object Oriented Programming through Java 4.1 Introduction to Polymorphism Polymorphism is the third essential feature of an object-oriented programming language, after data abstraction and inheritance. It provides another dimension of separation of interface from implementation, to decouple what from how. Polymorphism allows improved code organisation and readability as well as the creation of extensible programs that can be grown not only during the original creation of the project but also when new features are desired. Encapsulation creates new data types by combining characteristics and behaviors. Implementation hiding separates the interface from the implementation by making the details private. This sort of mechanical organization makes ready sense to someone with a procedural programming background. But polymorphism deals with decoupling in terms of types. The polymorphic method call allows one type to express its distinction from another, similar type, as long as they re both derived from the same base type. This distinction is expressed through differences in behavior of the methods that we can call through the base class. 4.2 Upcasting Revisited Taking an object reference and treating it as a reference to its base type is called upcasting, because of the way inheritance trees are drawn with the base class at the top. Example: //: c07:music:music.java // Inheritance & upcasting. class Note private int value; private Note(int val) value = val; public static final Note MIDDLE_C = new Note(0), C_SHARP = new Note(1), B_FLAT = new Note(2); // Etc. class Instrument public void play(note n) System.out.println( Instrument.play() ); // Wind objects are instruments // because they have the same interface: class Wind extends Instrument // Redefine interface method: public void play(note n) System.out.println( Wind.play() ); public class Music public static void tune(instrument i) //... i.play(note.middle_c); public static void main(string[] args) Wind flute = new Wind(); tune(flute); // Upcasting ///:~ 42

53 The method Music.tune( ) accepts an Instrument reference, but also anything derived from Instrument. In main( ), we can see this happening as a Wind reference is passed to tune( ), with no cast necessary. This is acceptable; the interface in Instrument must exist in Wind, because Wind is inherited from Instrument. Upcasting from Wind to Instrument may narrow that interface, but it cannot make it anything less than the full interface to Instrument. 4.3 Forgetting the Object Type The program above might seem strange. Why should anyone intentionally forget the type of an object? This is what happens when we upcast, and it seems like it could be much more straightforward if tune( ) simply takes a Wind reference as its argument. This brings up an essential point: If we did that, we d need to write a new tune( ) for every type of Instrument in our system. Suppose we follow this reasoning and add Stringed and Brass instruments: //: c07:music2:music2.java // Overloading instead of upcasting. class Note private int value; private Note(int val) value = val; public static final Note MIDDLE_C = new Note(0), C_SHARP = new Note(1), B_FLAT = new Note(2); // Etc. class Instrument public void play(note n) System.out.println( Instrument.play() ); class Wind extends Instrument public void play(note n) System.out.println( Wind.play() ); class Stringed extends Instrument public void play(note n) System.out.println( Stringed.play() ); class Brass extends Instrument public void play(note n) System.out.println( Brass.play() ); 43

54 Object Oriented Programming through Java public class Music2 public static void tune(wind i) i.play(note.middle_c); public static void tune(stringed i) i.play(note.middle_c); public static void tune(brass i) i.play(note.middle_c); public static void main(string[] args) Wind flute = new Wind(); Stringed violin = new Stringed(); Brass frenchhorn = new Brass(); tune(flute); // No upcasting tune(violin); tune(frenchhorn); ///:~ This works, but there s a major drawback: We must write type-specific methods for each new Instrument class we add. This means more programming in the first place, but it also means that if we want to add a new method like tune( ) or a new type of Instrument, we ve got a lot of work to do. Add the fact that the compiler won t give us any error messages if we forget to overload one of our methods and the whole process of working with types becomes unmanageable. It would be better if we could just write a single method that takes the base class as its argument, and not any of the specific derived classes. That s exactly what polymorphism allows us to do. The twist The difficulty with Music.java can be seen by running the program. The output is Wind.play( ). This is clearly the desired output, but it doesn t seem to make sense that it would work that way. Look at the tune( ) method: public static void tune(instrument i) //... i.play(note.middle_c); It receives an Instrument reference. So how can the compiler possibly know that this Instrument reference points to a Wind in this case and not a Brass or Stringed? The compiler can t. To get a deeper understanding of the issue, it s helpful to examine the subject of binding. 4.4 Method Calling Binding Connecting a method call to a method body is called binding. When binding is performed before the program is run (by the compiler and linker, if there is one), it s called early binding. We might not have heard the term before because it has never been an option with procedural languages. C compilers have only one kind of method call, and that s early binding. The confusing part of the above program revolves around early binding because the compiler cannot know the correct method to call when it has only an Instrument reference. 44

55 The solution is called late binding, which means that the binding occurs at run-time based on the type of object. Late binding is also called dynamic binding or run-time binding. When a language implements late binding, there must be some mechanism to determine the type of the object at run-time and to call the appropriate method. That is, the compiler still doesn t know the object type, but the method-call mechanism finds out and calls the correct method body. The late-binding mechanism varies from language to language, but we can imagine that some sort of type information must be installed in the objects. All method binding in Java uses late binding unless a method has been declared final. This means that ordinarily we don t need to make any decisions about whether late binding will occur it happens automatically. We declare a method final as it prevents anyone from overriding that method. Perhaps more important, it effectively turns off dynamic binding, or rather it tells the compiler that dynamic binding isn t necessary. This allows the compiler to generate slightly more efficient code for final method calls. However, in most cases it won t make any overall performance difference in our program, so it s best to only use final as a design decision, and not as an attempt to improve performance. 4.5 Producing the Right Behaviour After knowing that all method binding in Java happens polymorphically via late binding, we can write our code to talk to the base class and know that all the derived-class cases will work correctly using the same code. Or to put it another way, we send a message to an object and let the object figure out the right thing to do. The classic example in OOP is the shape example. This is commonly used because it is easy to visualize, but unfortunately it can confuse novice programmers into thinking that OOP is just for graphics programming, which is of course not the case. The shape example has a base class called Shape and various derived types: Circle, Square, Triangle, etc. The reason the example works so well is that it s easy to say a circle is a type of shape and be understood. The inheritance diagram shows the relationships: Cast "up" the inheritance diagram Shape draw ( ) erase ( ) Circle Square Triangle Circle Handle draw ( ) erase ( ) draw ( ) erase ( ) draw ( ) erase ( ) The upcast could occur in a statement as simple as: Fig. 4.1 Inheritance diagram Shape s = new Circle(); Here, a Circle object is created and the resulting reference is immediately assigned to a Shape, which would seem to be an error (assigning one type to another); and yet it s fine because a Circle is a Shape by inheritance. So the compiler agrees with the statement and doesn t issue an error message. 45

56 Object Oriented Programming through Java Suppose we call one of the base-class methods (that have been overridden in the derived classes): s.draw(); Again, we might expect that Shape s draw( ) is called because this is, after all, a Shape reference so how could the compiler know to do anything else? And yet the proper Circle.draw( ) is called because of late binding (polymorphism). The following example puts it a slightly different way. //: c07:shapes.java // Polymorphism in Java. class Shape void draw() void erase() class Circle extends Shape void draw() System.out.println( Circle.draw() ); void erase() System.out.println( Circle.erase() ); class Square extends Shape void draw() System.out.println( Square.draw() ); void erase() System.out.println( Square.erase() ); class Triangle extends Shape void draw() System.out.println( Triangle.draw() ); void erase() System.out.println( Triangle.erase() ); public class Shapes public static Shape randshape() switch((int)(math.random() * 3)) default: case 0: return new Circle(); case 1: return new Square(); case 2: return new Triangle(); public static void main(string[] args) Shape[] s = new Shape[9]; // Fill up the array with shapes: for(int i = 0; i < s.length; i++) s[i] = randshape(); // Make polymorphic method calls: for(int i = 0; i < s.length; i++) s[i].draw(); ///:~ 46

57 The base class Shape establishes the common interface to anything inherited from Shape that is, all shapes can be drawn and erased. The derived classes override these definitions to provide unique behavior for each specific type of shape. The main class Shapes contains a static method randshape( ) that produces a reference to a randomly-selected Shape object each time we call it. Note that the upcasting happens in each of the return statements, which take a reference to a Circle, Square, or Triangle and sends it out of the method as the return type, Shape. So, whenever we call this method we never get a chance to see what specific type it is, since you always get back a plain Shape reference. main( ) contains an array of Shape references filled through calls to randshape( ). At this point, we know we have Shapes, but we don t know anything more specific than that (and neither does the compiler). However, when we step through this array and call draw( ) for each one, the correct type-specific behavior magically occurs, as we can see from one output example: Circle.draw() Triangle.draw() Circle.draw() Circle.draw() Circle.draw() Square.draw() Triangle.draw() Square.draw() Square.draw() Of course, since the shapes are all chosen randomly each time, our runs will have different results. The point of choosing the shapes randomly is to drive home the understanding that the compiler can have no special knowledge that allows it to make the correct calls at compile-time. All the calls to draw( ) are made through dynamic binding. 4.6 Extensibility Now let s return to the musical instrument example. Because of polymorphism, we can add as many new types as we want to the system without changing the tune( ) method. In a well-designed OOP program, most or all of our methods will follow the model of tune( ) and communicate only with the base-class interface. Such a program is extensible because we can add new functionality by inheriting new data types from the common base class. The methods that manipulate the base-class interface will not need to be changed at all to accommodate the new classes. Consider what happens if we take the instrument example and add more methods in the base class and a number of new classes. Here s the diagram: 47

58 Object Oriented Programming through Java Instrument void play() String what() void adjust() Wind Percussion Stringed void play() String what() void adjust() void play() String what() void adjust() void play() String what() void adjust() Woodwind void play() String what() Brass void play() void adjust() Fig. 4.2 Addition of methods and classes to the instrument All these new classes work correctly with the old, unchanged tune( ) method. Even if tune( ) is in a separate file and new methods are added to the interface of Instrument, tune( ) works correctly without recompilation. Here is the implementation of the above diagram: //: c07:music3:music3.java // An extensible program. import java.util.*; class Instrument public void play() System.out.println( Instrument.play() ); public String what() return Instrument ; public void adjust() class Wind extends Instrument public void play() System.out.println( Wind.play() ); public String what() return Wind ; public void adjust() class Percussion extends Instrument public void play() System.out.println( Percussion.play() ); public String what() return Percussion ; public void adjust() 48

59 class Stringed extends Instrument public void play() System.out.println( Stringed.play() ); public String what() return Stringed ; public void adjust() class Brass extends Wind public void play() System.out.println( Brass.play() ); public void adjust() System.out.println( Brass.adjust() ); class Woodwind extends Wind public void play() System.out.println( Woodwind.play() ); public String what() return Woodwind ; public class Music3 // Doesn t care about type, so new types // added to the system still work right: static void tune(instrument i) //... i.play(); static void tuneall(instrument[] e) for(int i = 0; i < e.length; i++) tune(e[i]); public static void main(string[] args) Instrument[] orchestra = new Instrument[5]; int i = 0; // Upcasting during addition to the array: orchestra[i++] = new Wind(); orchestra[i++] = new Percussion(); orchestra[i++] = new Stringed(); orchestra[i++] = new Brass(); orchestra[i++] = new Woodwind(); tuneall(orchestra); ///:~ The new methods are what( ), which returns a String reference with a description of the class, and adjust( ), which provides some way to adjust each instrument. In main( ), when we place something inside the Instrument array we automatically upcast to Instrument. We can see that the tune( ) method is blissfully ignorant of all the code changes that have happened around it, and yet it works correctly. This is exactly what polymorphism is supposed to provide. Our code changes don t cause damage to parts of the program that should not be affected. Put another way, polymorphism is one of the most important techniques that allow the programmer to separate the things that change from the things that stay the same. 49

60 Object Oriented Programming through Java 4.7 Overriding vs Overloading In the following program, the interface of the method play( ) is changed in the process of overriding it, which means that we haven t overridden the method, but instead overloaded it. The compiler allows us to overload methods so it gives no complaint. But the behavior is probably not what we want. Here s the example: //: c07:winderror.java // Accidentally changing the interface. class NoteX public static final int MIDDLE_C = 0, C_SHARP = 1, C_FLAT = 2; class InstrumentX public void play(int NoteX) System.out.println( InstrumentX.play() ); class WindX extends InstrumentX // OOPS! Changes the method interface: public void play(notex n) System.out.println( WindX.play(NoteX n) ); public class WindError public static void tune(instrumentx i) //... i.play(notex.middle_c); public static void main(string[] args) WindX flute = new WindX(); tune(flute); // Not the desired behavior! ///:~ There s another confusing aspect thrown in here. In InstrumentX, the play( ) method takes an int that has the identifier NoteX. That is, even though NoteX is a class name, it can also be used as an identifier without complaint. But in WindX, play( ) takes a NoteX reference that has an identifier n. (Although we could even say play(notex NoteX) without an error.) Thus it appears that the programmer intended to override play( ) but mistyped the method a bit. The compiler, however, assumed that an overload and not an override was intended. Note that if we follow the standard Java naming convention, the argument identifier would be notex (lowercase n ), which would distinguish it from the class name. In tune, the InstrumentX i is sent the play( ) message, with one of NoteX s members (MIDDLE_C) as an argument. Since NoteX contains int definitions, this means that the int version of the now-overloaded play( ) method is called, and since that has not been overridden the base-class version is used. The output is: InstrumentX.play() This certainly doesn t appear to be a polymorphic method call. Once we understand what s happening, we can fix the problem fairly easily. 50

61 4.8 Abstract Classes and Methods In all the instrument examples, the methods in the base class Instrument were always dummy methods. If these methods are ever called, we ve done something wrong. That s because the intent of Instrument is to create a common interface for all the classes derived from it. The only reason to establish this common interface is so it can be expressed differently for each different subtype. It establishes a basic form, so we can say what s in common with all the derived classes. Another way of saying this is to call Instrument an abstract base class (or simply an abstract class). We create an abstract class when we want to manipulate a set of classes through this common interface. All derived-class methods that match the signature of the base-class declaration will be called using the dynamic binding mechanism. If we have an abstract class like Instrument, objects of that class almost always have no meaning. That is, Instrument is meant to express only the interface, and not a particular implementation, so creating an Instrument object makes no sense, and we ll probably want to prevent the user from doing it. This can be accomplished by making all the methods in Instrument print error messages, but that delays the information until run-time and requires reliable exhaustive testing on the user s part. It s always better to catch problems at compile-time. Java provides a mechanism for doing this called the abstract method. This is a method that is incomplete; it has only a declaration and no method body. Here is the syntax for an abstract method declaration: abstract void f() A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, the class must be qualified as abstract. (Otherwise, the compiler gives us an error message.) If an abstract class is incomplete, what is the compiler supposed to do when someone tries to make an object of that class? It cannot safely create an object of an abstract class, so we get an error message from the compiler. This way the compiler ensures the purity of the abstract class, and we don t need to worry about misusing it. If we inherit from an abstract class and we want to make objects of the new type, we must provide method definitions for all the abstract methods in the base class. If we don t, then the derived class is also abstract and the compiler will force us to qualify that class with the abstract keyword. It s possible to create a class as abstract without including any abstract methods. This is useful when we ve got a class in which it doesn t make sense to have any abstract methods, and yet we want to prevent any instances of that class. The Instrument class can easily be turned into an abstract class. Only some of the methods will be abstract, since making a class abstract doesn t force us to make all the methods abstract. Here s what it looks like: 51

62 Object Oriented Programming through Java abstract Instrument abstract void play() ; String what() /*... */ abstract void adjust() ; extends extends extends Wind void play() String what() void adjust() Percussion void play() String what() void adjust() Stringed void play() String what() void adjust() extends Woodwind void play() String what() extends Brass void play() void adjust() Fig. 4.3 Instrument class into abstract class Here s the orchestra example modified to use abstract classes and methods: //: c07:music4:music4.java // Abstract classes and methods. import java.util.*; abstract class Instrument int i; // storage allocated for each public abstract void play(); public String what() return Instrument ; public abstract void adjust(); class Wind extends Instrument public void play() System.out.println( Wind.play() ); public String what() return Wind ; public void adjust() class Percussion extends Instrument public void play() System.out.println( Percussion.play() ); public String what() return Percussion ; public void adjust() 52

63 class Stringed extends Instrument public void play() System.out.println( Stringed.play() ); public String what() return Stringed ; public void adjust() class Brass extends Wind public void play() System.out.println( Brass.play() ); public void adjust() System.out.println( Brass.adjust() ); class Woodwind extends Wind public void play() System.out.println( Woodwind.play() ); public String what() return Woodwind ; public class Music4 // Doesn t care about type, so new types // added to the system still work right: static void tune(instrument i) //... i.play(); static void tuneall(instrument[] e) for(int i = 0; i < e.length; i++) tune(e[i]); public static void main(string[] args) Instrument[] orchestra = new Instrument[5]; int i = 0; // Upcasting during addition to the array: orchestra[i++] = new Wind(); orchestra[i++] = new Percussion(); orchestra[i++] = new Stringed(); orchestra[i++] = new Brass(); orchestra[i++] = new Woodwind(); tuneall(orchestra); ///:~ We can see that there s really no change except in the base class. It s helpful to create abstract classes and methods because they make the abstractness of a class explicit, and tell both the user and the compiler how it was intended to be used. 4.9 Constructors and Polymorphism Constructors are different from other kinds of methods. This is also true when polymorphism is involved. Even though constructors are not polymorphic, it s important to understand the way constructors work in complex hierarchies and with polymorphism. This understanding will help us avoid unpleasant entanglements. 53

64 Object Oriented Programming through Java Order of Constructor Calls A constructor for the base class is always called in the constructor for a derived class, chaining up the inheritance hierarchy so that a constructor for every base class is called. This makes sense because the constructor has a special job: to see that the object is built properly. A derived class has access to its own members only, and not to those of the base class (whose members are typically private). Only the base-class constructor has the proper knowledge and access to initialise its own elements. Therefore, it s essential that all constructors get called; otherwise the entire object wouldn t be constructed. That s why the compiler enforces a constructor call for every portion of a derived class. It will silently call the default constructor if we don t explicitly call a base-class constructor in the derivedclass constructor body. If there is no default constructor, the compiler will complain. Let s take a look at an example that shows the effects of composition, inheritance, and polymorphism on the order of construction: //: c07:sandwich.java // Order of constructor calls. class Meal Meal() System.out.println( Meal() ); class Bread Bread() System.out.println( Bread() ); class Cheese Cheese() System.out.println( Cheese() ); class Lettuce Lettuce() System.out.println( Lettuce() ); class Lunch extends Meal Lunch() System.out.println( Lunch() ); class PortableLunch extends Lunch PortableLunch() System.out.println( PortableLunch() ); class Sandwich extends PortableLunch Bread b = new Bread(); Cheese c = new Cheese(); Lettuce l = new Lettuce(); Sandwich() System.out.println( Sandwich() ); public static void main(string[] args) new Sandwich(); ///:~ This example creates a complex class out of other classes, and each class has a constructor that announces itself. The important class is Sandwich, which reflects three levels of inheritance (four, if we count the implicit inheritance from Object) and three member objects. When a Sandwich object is created in main( ), the output is: 54

65 Meal() Lunch() PortableLunch() Bread() Cheese() Lettuce() Sandwich() This means that the order of constructor calls for a complex object is as follows: 1. The base-class constructor is called. This step is repeated recursively such that the root of the hierarchy is constructed first, followed by the next-derived class, etc., until the most-derived class is reached. 2. Member initialisers are called in the order of declaration. 3. The body of the derived-class constructor is called. The order of the constructor calls is important. When we inherit, we know all about the base class and can access any public and protected members of the base class. This means that we must be able to assume that all the members of the base class are valid when we re in the derived class. In a normal method, construction has already taken place, so all the members of all parts of the object have been built. Inside the constructor, however, we must be able to assume that all members that we use have been built. The only way to guarantee this is for the base-class constructor to be called first. Then when we re in the derived-class constructor, all the members we can access in the base class have been initialised. Knowing that all members are valid inside the constructor is also the reason that, whenever possible, we should initialize all member objects (that is, objects placed in the class using composition) at their point of definition in the class (e.g., b, c, and 1 in the example above). If we follow this practice, we will help ensure that all base class members and member objects of the current object have been initialised 55

66 Object Oriented Programming through Java Summary Polymorphism allows improved code organisation and readability as well as the creation of extensible programs that can be grown not only during the original creation of the project but also when new features are desired. The polymorphic method call allows one type to express its distinction from another, similar type, as long as they re both derived from the same base type. This distinction is expressed through differences in behavior of the methods that we can call through the base class. Taking an object reference and treating it as a reference to its base type is called upcasting, because of the way inheritance trees are drawn with the base class at the top. Connecting a method call to a method body is called binding. When binding is performed before the program is run (by the compiler and linker, if there is one), it s called early binding. Late binding, means that the binding occurs at run-time based on the type of object. Late binding is also called dynamic binding or run-time binding. All method binding in Java uses late binding unless a method has been declared final. This means that ordinarily we don t need to make any decisions about whether late binding will occur it happens automatically. A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, the class must be qualified as abstract. If we inherit from an abstract class and we want to make objects of the new type, we must provide method definitions for all the abstract methods in the base class. A constructor for the base class is always called in the constructor for a derived class, chaining up the inheritance hierarchy so that a constructor for every base class is called. References Balaguruswamy, E., Programming with Java - A Primer, 3/e. 7 th ed., Tata McGraw Hill publishing company limited. Umbarger, D., An Introduction to Polymorphism in Java, [online]. Available at:< collegeboard.com/apc/public/repository/intro_to_polymorphismin_umbargar.pdf>.[accessed 12 April 2011] Javapassion.com, Polymorphism, [online]. Available at: < pdf>. [Accessed 12 April 2011] Recommended Reading Schildt, H., Java: A Beginner s Guide. 4 th ed., McGraw-Hill Osborne Media. Hunt, J., Java and Object Orientation. 2 nd ed., Springer. Kak, A., Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java. 1 st ed., Wiley-IEEE Press. 56

67 Self Assessment 1. All derived-class methods that match the signature of the base-class declaration will be called using the: a. Dynamic binding mechanism b. Error-time binding mechanism c. Static binding mechanism d. Early binding mechanism Connecting a method call to a method body is called. a. connection b. binding c. inheriting d. upcasting Taking an object reference and treating it as a reference to its base type is called: a. Linking b. Extensibility c. Binding d. Upcasting Encapsulation creates new types by combining characteristics and behaviors. a. object b. class c. data d. function Which of the following statements is FALSE? a. The order of the constructor calls is important. b. When we inherit, we know all about the base class and can access any public and protected members of the base class. c. All method binding in Java uses early binding unless a method has been declared final. d. The late-binding mechanism varies from language to language, but we can imagine that some sort of type information must be installed in the objects. Which of the following statement is true? a. When binding is performed before the program is run it s called late binding b. When a language implements late binding, there must be some mechanism to determine the type of the object at error-time and to call the appropriate method. c. We declare a method final as it prevents anyone from overloading that method. d. The methods that manipulate the base-class interface will not need to be changed at all to accommodate the new classes. 57

68 Object Oriented Programming through Java All method binding in Java uses late binding unless a method has been declared. a. important b. final c. public d. private Late binding is also called: a. dynamic binding mechanism b. error-time binding mechanism c. static binding mechanism d. early binding mechanism Which of the following method is incomplete it has only a declaration and no method body? a. Abstract method b. Interface method c. Overloading method d. Overriding method 10. A derived class has access to its own members only, and not to those of the class. a. declared b. method c. base d. object 58

69 Chapter V Exception Handling Aim The aim of this chapter is to: introduce the concept of exception handling explain how to throw an exception discuss about advertising the exceptions that a method throws Objectives The objectives of this chapter are to: get an overview of rethrowing exceptions explain the concept of the finally clause describe the classification of exceptions Learning outcome At the end of this chapter, you will be able to: understand the concept of catching exceptions deal with errors know to create exception classes 59

70 Object Oriented Programming through Java 5.1 Introduction to Exception Handling The ideal time to catch an error is at compile-time, before we even try to run the program. However, not all errors can be detected at compile-time. The rest of the problems must be handled at run-time, through some formality that allows the originator of the error to pass appropriate information to a recipient who will know how to handle the difficulty properly. For exceptional situations, such as bad input data with the potential to bomb the program, Java uses a form of error-trapping called, exception handling. Exception handling in Java is similar to that in C Dealing with Errors Suppose an error occurs while a Java program is running. The error might be caused by a file containing wrong information, a flaky network connection, or use of an invalid array index or an attempt to use an object reference that hasn t yet been assigned to an object. Users expect that programs will act sensibly when errors happen. If an operation cannot be completed because of an error, the program ought to either: Return to a safe state and enable the user to execute other commands; OR Allow the user to save all his or her work and terminate the program gracefully. This may not be easy to do: the code that detects the error condition is usually far removed from the code that can roll back the data to a safe state, or the code that can save the user s work and exit cheerfully. The mission of exception handling is to transfer control from where the error occurred to an error-handler that can deal with the situation. To handle exceptional situations in our program, we must take into account the errors and problems that may occur. The problems that we need consider are: user input errors device errors physical limitations code errors 5.2 The Classification of Exceptions In Java, an exception object is always an instance of a class derived from throwable. Throwable Error Exception IOException Runtime Exception Fig. 5.1 Exception hierarchy in Java 60

71 Notice that all exceptions descend from throwable, but the hierarchy immediately splits into two branches: error and exception. The error hierarchy describes internal errors and resource exhaustion inside the Java runtime system. We should not throw an object of this type. There is little we can do if such an internal error occurs, beyond notifying the user and trying to terminate the program gracefully. These situations are quite rare. When doing Java programming, we focus on the exception hierarchy. The exception hierarchy also splits into two branches: exceptions that derive from runtime exception and those that do not. The general rule is this: A runtime exception happens because we made a programming error. Any other exception occurs because a bad thing, such as an I/O error, happened to our otherwise good program. Exceptions that inherit from runtime exception include problems such as: a bad cast an out-of-bounds array access a null pointer access Exceptions that do not inherit from runtime exception include: trying to read past the end of a file; trying to open a malformed URL; trying to find a class object for a string that does not denote an existing class. The rule If it is a RuntimeException, it is our fault works pretty well. We could have avoided that ArrayIndexOutOfBoundsException by testing the array index against the array bounds. The NullPointerException would not have happened if we would had checked whether or not the variable was null before using it. The Java Language Specification calls any exception that derives from the class Error or the class RuntimeException an unchecked exception. All other exceptions are called checked exceptions. This is useful terminology that we will also adopt. 5.3 Advertising the Exceptions that a Method Throws A Java method can throw an exception if it encounters a situation it cannot handle. The idea is simple: a method will not only tell the Java compiler what values it can return, it will also the compiler what can go wrong. For example, code that attempts to read from a file knows that the file might not exist or that it might be empty. The code that tries to process the information in a file therefore will need to notify the compiler that it can throw some sort of IOException. The place where we advertise that our method can throw an exception is in the header of the method; the header changes to reflect the checked exceptions the method can throw. For example, here is the header for a method in the BufferedReader class from the standard library. The method reads a line of text from a stream, such as a file or network connection. public String readline( ) throws IOException The header indicates this method returns a string, but it also has the capacity to go wrong in a special way by throwing an IOException. When we write our own methods, we don t have to advertise every possible throwable object that our method might actually throw. To understand when (and what) we have to advertise in the throws clause of the methods we write, keep in mind that an exception is thrown in any of the following four situations: 61

72 Object Oriented Programming through Java We call a method that throws a checked exception, for example, the readline method of the BufferedReader class. We detect an error and throw a checked exception with the throw statement We make a programming error, such as a[-1] = 0 that gives rise to an unchecked exception such as an ArrayIndexOutOfBoundsException. An internal error occurs in the virtual machine or runtime library. As with Java methods that are part of the supplied classes, we declare that our method may throw an exception with an exception specification in the method header. class MyAnimation... public Image loadimage(string s) throws IOException... If a method throws more than one checked exception, we must indicate all exceptions in the header. Separate them by a comma as in the following example: class MyAnimation... public Image loadimage(string s) throws EOFException, MalformedURLException... However, we do not need to advertise internal Java errors, that is, exceptions inheriting from Error. Any code could potentially throw those exceptions, and they are entirely beyond our control. Similarly, we should not advertise unchecked exceptions inheriting from RuntimeException. class MyAnimation... void drawimage(int i) throws ArrayIndexOutOfBoundsException // NO!!!... These runtime errors are completely under our control. 62

73 5.4 How to Throw an Exception Let us suppose something terrible has happened in our code. We have a method, readdata, that is reading in a file whose header promised Content-length: 1024 But, we get an end of file after 733 characters. We decide this situation is so abnormal that we want to throw an exception. We need to decide what exception type to throw. Some kind of IOException would be a good choice. Perusing the Java API documentation, we find an EOFException with the description Signals that an EOF has been reached unexpectedly during input. Perfect. Here is how we throw it: throw new EOFException(); or, EOFException e = new EOFException(); throw e; Here is how it all fits together: String readdata(bufferedreader in) throws EOFException... while (...) if (ch == -1) // EOF encountered if (n < len) throw new EOFException();... return s; The EOFException has a second constructor that takes a string argument. We can put this to good use by describing the exceptional condition more carefully. String gripe = Content-length: + len +, Received: + n; throw new EOFException(gripe); As we can see, throwing an exception is easy if one of the existing exception classes works for us. In this case: find an appropriate exception class make an object of that class throw it Once a method throws an exception, the method does not return to its caller. This means that we do not have to worry about cooking up a default return value or an error code. 63

74 Object Oriented Programming through Java 5.5 Creating Exception Classes Our code may run into a problem that is not adequately described by any of the standard exception classes. In this case, it is easy enough to create our own exception class. Just derive it from Exception or from a child class of Exception such as IOException. It is customary to give both a default constructor and a constructor that contains a detailed message. class FileFormatException extends IOException public FileFormatException() public FileFormatException(String gripe) super(gripe); Now we are ready to throw our very own exception type. String readdata(bufferedreader in) throws FileFormatException... while (...) if (ch == -1) // EOF encountered if (n < len) throw new FileFormatException();... return s; Throwable(): constructs a new Throwable object with no detailed message. Throwable(String message): constructs a new Throwable object with the specified detailed message. By convention, all derived exception classes support both a default constructor and a constructor with a detailed message. String getmessage(): gets the detailed message of the Throwable object. 5.6 Catching Exceptions We now know how to throw an exception. It is pretty easy. We throw it and forget it. Of course, some code has to catch the exception. Catching exceptions requires more planning. If an exception occurs that is not caught anywhere in a nongraphical application, the program will terminate and print a message to the console giving the type of the exception and a stack trace. A graphics program (both an applet and an application) prints the same error message, but the program goes back to its user interface processing loop. (When we are debugging a graphically based program, it is a good idea to keep the console available on the screen and not minimized.) 64

75 To catch an exception, we set up a try/catch block. The simplest form of the try block is as follows: try code more code more code catch (ExceptionType e) handler for this type If any of the code inside the try block throws an exception of the class specified in the catch clause, then, The program skips the remainder of the code in the try block. The program executes the handler code inside the catch clause If none of the code inside the try block throws an exception, then the program skips the catch clause. If any of the code in a method throws an exception of a type other than the one named in the catch clause, this method exits immediately. To show this at work, here is some fairly typical code for reading in text: public void read(bufferedreader reader) try boolean done = false; while (!done) String line = reader.readline(); if (line == null) // end of file done = true; else process line; catch (IOException exception) exception.printstacktrace(); Notice that most of the code in the try clause is straightforward: it reads and processes lines until we encounter the end of the file. As we can see by looking at the Java API, there is the possibility that the readline method will throw an IOException. In that case, we skip out of the entire while loop, enter the catch clause and generate a stack trace. Often, the best choice is to do nothing at all. If an error occurs in the readline method, let the caller of the read method worry about it! If we take that approach, then we have to advertise the fact that the method may throw an IOException. 65

76 Object Oriented Programming through Java public void read(bufferedreader reader) throws IOException boolean done = false; while (!done) String line = reader.readline(); if (line == null) // end of file done = true; else process line; Remember, the compiler strictly enforces the throws specifiers. If we call a method that throws a checked exception, we must either handle it or pass it on. Which of the two is better? As a general rule, we should catch those exceptions that we know how to handle, and propagate those that we do not know how to handle. When we propagate an exception, we must add a throws specifier to alert the caller that an exception may be thrown. 5.7 Catching Multiple Exceptions We can catch multiple exception types in a try block and handle each type differently. We use a separate catch clause for each type as in the following example: try code that might throw exceptions catch (MalformedURLException e1) // emergency action for malformed URLs catch (UnknownHostException e2) // emergency action for unknown hosts catch (IOException e3) // emergency action for all other I/O problems The exception object (e1, e2, e3) may contain information about the nature of the exception. To find out more about the object, try e3.getmessage() to get the detailed error message (if there is one), or e3.getclass().getname() to get the actual type of the exception object. 66

77 5.8 Rethrowing Exceptions Occasionally, we need to catch an exception without addressing the root cause of it. This need typically occurs when we have to do some local cleanup but can t fully resolve the problem. We then want to take our emergency action and again call throw to send the exception back up the calling chain. We can see a typical example of this in the following code. Graphics g = image.getgraphics(); try code that might throw exceptions catch (MalformedURLException e) g.dispose(); throw e; The above code shows one of the most common reasons for having to rethrow an exception that we have caught. If we do not dispose of the graphics context object in the catch clause, it will never be disposed of. On the other hand, the underlying cause, the malformed URL exception, has not disappeared. We still want to report it to the authorities, who presumably know how to deal with such an exception. We can also throw a different exception than the one we catch. try acme.util.widget a = new acme.util.widget(); a.load(s); a.paint(g); catch (RuntimeException e) // sheesh another ACME error throw new Exception( ACME error ); The finally Clause When our code throws an exception, it stops processing the remaining code in our method and exits the method. This is a problem if the method has acquired some local resource that only it knows about and if that resource must be cleaned up. One solution is to catch and rethrow all exceptions. But this solution is tedious because you need to clean up the resource allocation in two places, in the normal code and in the exception code. Java has a better solution, the finally clause: Graphics g = image.getgraphics(); try code that might throw exceptions catch (IOException e) show error dialog 67

78 Object Oriented Programming through Java finally g.dispose(); This program executes the code in the finally clause whether or not an exception was caught. This means, in the example code above, the program will dispose of the graphics context under all circumstances. Let us look at the three possible situations where the program will execute the finally clause. The code throws no exceptions. In this event, the program first executes all the code in the try block. Then, it executes the code in the finally clause. Afterwards, execution continues with the first line after the try block. The code throws an exception that is caught in a catch clause, in our case, an IOException. For this, the program executes all code in the try block, up to the point at which the exception was thrown. The remaining code in the try block is skipped. Then, the program executes the code in the matching catch clause, then the code in the finally clause. If the catch clause does not throw an exception, then the program executes the first line after the try block. If it does, then the exception is thrown back to the caller of this method. The code throws an exception that is not caught in any catch clause. For this, the program executes all code in the try block until the exception is thrown. The remaining code in the try block is skipped. Then, the code in the finally clause is executed, and the exception is thrown back to the caller of this method. We can use the finally clause without a catch clause. For example, consider the following try statement: Graphics g = image.getgraphics(); try code that might throw exceptions finally g.dispose(); The g.dispose() command in the finally clause is executed whether or not an exception is encountered in the try block. Of course, if an exception is encountered, it is rethrown and must be caught in another catch clause. 68

79 Summary For exceptional situations, such as bad input data with the potential to bomb the program, Java uses a form of error-trapping called, exception handling. If an operation cannot be completed because of an error, the program ought to either: return to a safe state and enable the user to execute other command, or allow the user to save all his or her work and terminate the program gracefully. The mission of exception handling is to transfer control from where the error occurred to an error-handler that can deal with the situation. To handle exceptional situations in our program, we must take into account the errors and problems that may occur. The problems that we need consider are: user input errors, device errors, physical limitations, and code errors. In Java, an exception object is always an instance of a class derived from throwable. All exceptions descend from throwable, but the hierarchy immediately splits into two branches: error and exception. The error hierarchy describes internal errors and resource exhaustion inside the Java runtime system. When doing Java programming, we focus on the exception hierarchy. The exception hierarchy also splits into two branches: exceptions that derive from runtime exception and those that do not. A Java method can throw an exception if it encounters a situation it cannot handle. The idea is simple: a method will not only tell the Java compiler what values it can return, it will also the compiler what can go wrong. Catching exceptions require more planning. If an exception occurs that is not caught anywhere in a nongraphical application, the program will terminate and print a message to the console giving the type of the exception and a stack trace. References Balaguruswamy, E., Programming with Java - A Primer, 3/e. 7 th ed., Tata McGraw Hill publishing company limited. Javapassion.com, [online]. Java Exception Handling. Available at : javaexceptions.pdf. [Accessed on 15 April 2011]. Recommended Reading Stelting, S., Robust Java: Exception Handling, Testing, and Debugging. Prentice Hall Poo, D. & Kiong, D., Object-Oriented Programming and Java. 2 nd ed., Springer. st Ibsen, C. & Anstey, J., Camel in Action. 1 ed., Manning Publications. 69

80 Object Oriented Programming through Java Self Assessment 1. The error hierarchy describes errors and resource exhaustion inside the Java runtime system. a. external b. internal c. object-oriented d. run-time A Java method can throw an exception if it encounters a situation it: a. cannot handle b. c. d. can handle can derive can compile The mission of exception handling is to control from where the error occurred to an error-handler that can deal with the situation. a. manage b. c. d. change transfer handle Which of the following statements if false? a. Our code may run into a problem that is not adequately described by any of the standard exception classes. b. c. d. Once a method throws an exception, the method does not return to its caller. A Java method can throw an exception if it encounters a situation it can handle. When doing Java programming, we focus on the exception hierarchy. A exception happens because we made a programming error. a. runtime b. c. d. nullpointer unchecked throwable The place where we advertise that our method can throw an exception is in the of the method. a. string b. c. d. hierarchy body header Which of the following statements is TRUE? a. Users expect that programs will act insensibly when errors happen. b. c. The ideal time to catch an error is at run-time, before we even try to run the program. In Java, an exception object is always an instance of a class derived from throwable. d. When we write our own methods, we have to advertise every possible throwable object that our method might actually throw. 70

81 8. In Java, an exception object is always an instance of a class derived from. a. object b. throwable c. error d. method 9. When we propagate an exception, we must add a throws specifier to alert the caller that an: a. exception may be thrown b. exception may be handled c. exception may be rethrown d. exception may be cancelled 10. If we call a method that throws a exception, we must either handle it or pass it on. a. unchecked b. checked c. runtime d. nullpointer 71

82 Object Oriented Programming through Java Chapter VI Object Oriented Programming Aim The aim of this chapter is to: state the basic concepts of object oriented programming discuss different language paradigms explain the data abstraction and encapsulation in detail Objectives The objectives of this chapter are to: elucidate the complete view of class determine the characteristics of object oriented programming explain object orientation Learning outcome At the end of this chapter, you will be able to: understand the advantages of object oriented programming evaluate the scope of class and its members recognise the scope of operator 72

83 6.1 Introduction to OOP Object oriented programming, also known as OOP, is a computer science term which is used to describe a computer application composed of multiple objects connected to each other. Traditionally, most computer programming languages were simply a group of functions or instructions. With OOP, every object can handle data, get messages, and transfer messages to other objects. The objects will all act as independent units in their own right, and they will be responsible for carrying out a certain process. Because the objects are not dependent on each other, OOP is seen as being more flexible than older methods of programming. It has become quite popular, and it is now used in a number of advanced software engineering projects. Many programmers feel that object oriented programming is easier for beginners to learn than previous programming methods. Because it is easier to learn, it can also be analysed and maintained without much difficulty. However, there are some people who feel that OOP is more complicated than older programming methods. To understand object oriented programming, there are a few concepts that we need to become familiar with. These are discussed below Class A class creates the attributes of a thing, and it will also define the processes that the thing can carry out. For example, a class called cats will have the attributes which are commonly found with cats, such as the ability to purr. A class will bring about modularity within the object oriented computer application. Someone who is not a programmer should be able to find a class. The reason for this is because the attributes of the class should be something that will make sense to them. It is also important for the code of a class to be self contained to a certain degree. When code is written with relevant names, it will be easier to understand. Make sure the code is self-contained which will allow one part of the application to be updated without the need to change the other parts. It is this modularity that makes OOP an effective programming method. It will also help the application solve the problems that it was designed for Object An object can be defined as a specific instance of a class. As an example, while the class Cats will provide all the attributes that are found in all cats, the object named Betsy is a specific cat. While it shares the same attributes which are found in all cats, it has fur with a unique colour. In object oriented programming, a programmer would say that the object Betsy is a run-time instance of the class Cats. A class may also be divided into sub-groups. Certain variations of a class may not be a specific object. The class Cats may have a sub-group which consists of multiple cat breeds. For example, if Betsy were a Persian cat, it would be an instance of the Persian cat sub-group. Every object within an OOP language will share some attributes with the parent class, but it will also have unique attributes as well. 73

84 Object Oriented Programming through Java Method A method may also be called a message and can be defined as the abilities of an object. Because Betsy is a cat, Betsy can purr. Because of this, purr is a method that Betsy has. Betsy may have a number of other methods. When a method is used within an object oriented programming language, it will only affect a single object. This is true even if the method is designed for the entire class. While all cats can purr, we will only need one cat to do it. Methods can further be broken down into commands, call-backs, or queries. A query will tell us about the state of the object, and a command will cause that object to carry out a task. A call-back is a method that is composed of a part within an object. The part will notify its parent that an event has taken place, and the object may need to react to the event. 6.2 Basic Concepts of Object Oriented Programming The basic concepts used extensively in object oriented programming are as follows: Objects Classes Data abstraction and encapsulation Inheritance Polymorphism Dynamic binding Message passing Objects An object can be considered a thing that can perform a set of related activities. The set of activities that the object performs defines the object s behaviour. For example, the hand can grip something or a Student (object) can give the name or address. In pure OOP terms an object is an instance of a class. Object is defined as an identifiable entity with some characteristic and behaviour. For instance, we can say Orange is an object. Its characteristics are: it is spherical shaped; its colour is orange, etc. Its behaviour is: it is juicy and it tastes sweet-sour. While programming using OOP approach, the characteristics of an object are represented by its data and its behaviour is represented by its functions associated. Therefore, in OOP programming object represents an entity that can store data and has its interface through functions. Programming problem is analysed in terms of objects and the nature of communication between them, so it is necessary for us to understand the nature of communication between objects. 74

85 6.2.2 Classes We have studied that objects contain data, and code to manipulate that data. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In other words, objects are variables of the type class. Once a class has been defined, we can create any number of objects belonging to that class. Each object is associated with the data of type class with which they are created. A class is thus a collection of objects of similar type. For example, mango, apple and orange are members of the class fruit. Classes are user-defined data types and behave like the built-in types of a programming language. The syntax used to create an object is no different than the syntax used to create an integer object on C. If fruit has been defined as a class, then the statement fruit mango; will create an object mango belonging to the class fruit Data Abstraction and Encapsulation The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world, and only these functions which are wrapped in the class can access it. The encapsulation is the inclusion within a program object of all the resources needed for the object to function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do. Abstraction refers to the act of representing essential features without including the background details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, weight and cost, and functions to operate on these attributes. They encapsulate all the essential properties of the objects that are to be created. The attributes are sometimes called data members because they hold information. The functions that operate on these data are sometimes called methods or member functions. Since the classes use the concept of data abstraction, they are known as Abstract Data Types (ADT) Inheritance Inheritance is the process by which objects of one class obtain the properties of objects of another class. It supports the concept of hierarchical classification. For example, the bird robin is a part of the class flying bird which is again a part of the class bird. The principle behind this sort of division is that each derived class shares common characteristics with the class from which it is derived as shown in the figure below. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features of an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have the combined features of both the classes. The real appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that is almost, but not exactly, what has been planned. Each sub-class defines only those features that are unique to it. Without the use of classification, each class would have to explicitly include all of its features. 75

86 Object Oriented Programming through Java Bird Attributes Feathers Lay eggs Flying Bird Attributes Nonflying Bird Attributes Robin Swallow Penguin Robin Attributes Attributes Attributes Attributes Fig. 6.1 Property inheritance Polymorphism Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more than one form. An operation may exhibit different behaviours in different instances. Behaviour depends upon the types of data used in the operation. For example, consider the operation of addition. For two numbers, the operation will generate a sum. If the operands are strings, then the operation would produce a third string by concatenation. The process of making an operator to exhibit different behaviours in different instances is known as operator overloading. The figure given below illustrates that a single function name can be used to handle different number and different types or arguments. This is something similar to a particular world having several different meanings depending on the context. Using a single function name to perform different types of tasks is known as function overloading. Polymorphism plays an important role in allowing objects having different internal structures to share the same external interface. This means that a general class of operations may be accessed in the same manner even though specific actions associated with each operation may differ. Polymorphism is extensively used in implementing inheritance. Shape Draw() Circle-object Draw(circle) Box-object Draw(box) Triangle-object Draw(triangle) Fig. 6.2 Polymorphism 76

87 6.2.6 Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with a polymorphic reference depends on the dynamic type of that reference. Consider the procedure draw in the fig 6.2. By inheritance, every object will have this procedure. Its algorithm is, however, unique to each object and so the draw procedure will be redefined in each class that defines the object. At run-time, the code matching the object under current reference will be called Message Passing An object oriented program consists of a set of objects that communicate with each other. The process of programming in an object oriented language, therefore, involves the following basic steps: creating classes that define objects and their behaviour creating objects from class definitions establishing communication among objects Objects communicate with one another by sending and receiving information much the same way as people pass messages to one another. The concept of message passing makes it easier to talk about building systems that directly model or simulate their real-world counterparts. A message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in the receiving object, the name of the function (message) and the information to be sent. Example is as shown below: employee.salary (name); object information message Fig. 6.3 Message passing Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible as long as it is alive. 6.3 Paradigms of Programming Languages The term paradigm describes a set of techniques, methods, theories and standards that together represent a way of thinking for problem solving. According to [Wegner, 1988], paradigms are patterns of thought for problem solving. Language paradigms were associated with classes of languages. First the paradigms are defined. Thereafter, programming languages according to the different paradigms are classified. The language paradigms are divided into two parts: imperative and declarative paradigms as shown in fig Imperative languages can be further classified into procedural and object oriented approach. Declarative languages can be classified into functional languages and logical languages. In the figure below, the examples of languages in each category are also given. 77

88 Object Oriented Programming through Java Language Paradigm Imperative Paradigm Declarative Paradigm Procedural Object Oriented Functional Logical C, Pascal C++, Simula, Java Lisp Prolog Imperative Paradigms Fig. 6.4 Language paradigm The meaning of imperative is expressing a command or order. So, the programming languages in this category specify the step-by-step explanation of command. Imperative programming languages describe how the results are to be obtained in terms of the underlying machine model. The programs specify step-by-step the entire set of transitions that a program goes through. The program starts from an initial state, goes through the transitions and reaches a final state. Within this paradigm, we have the procedural approach and object oriented approach. Procedural Paradigm Object oriented Paradigm Procedural languages are statement oriented with the variables holding values. In this language the execution of a program is modelled as a series of states of variable locations. We have two kinds of statements. Non-executable statements allocate memory, bind symbolic names to absolute memory locations and initialise memory. The popular programming languages in this category are Ada, FORTRAN, Basic, Algol, Pascal, COBOL, Modula, C, etc. The object oriented paradigm is centred on the concept of the object. Everything is focused on objects. Can we think what an object is? In this language, program consists of two things: first, a set of objects and second, the way they interact with each other. Computation in this paradigm is viewed as the simulation of real world entities. The popular programming languages in this paradigm are C++, Smalltalk and Java Declarative Paradigm Table 6.1 Procedural and object oriented paradigms In this paradigm, programs declare or specify what is to be computed without specifying how it is to be achieved. Declarative programming is also known as value-oriented programming. Declarative languages describe the relationship between variables in terms of functions and inference rules. 78

89 The language executor applies a fixed method to these relations to produce a desired result. It is mainly used in solving artificial intelligence and constraint-satisfaction problems. Declarative paradigm is further divided into two categories: functional and logical paradigms. Functional Paradigm In this paradigm, a programme consists of a collection of functions. A function just calculates and returns a value. A program consists of calling a function with appropriate arguments, but any function can make use of other functions also. The main programming languages in this category are Lisp, ML Scheme, and Haskell. Logical Paradigm In this paradigm programs only explain what is to be computed not how to compute it. Here program is represented by a set of relationships, between objects or property of objects known as predicate which are held to be true, and a set of logic/clauses (i.e., if A is true, then B is true). Normally, logical paradigm, integrates data and control structures. The Prolog language is perhaps the most common example. Mercury language is a more modern attempt at creating a logic programming language. 6.4 Programming Table 6.2 Functional and logical paradigms Programming is an art, which has been through many evolutions. The basic idea for evolution was to develop simpler, maintainable, dependable, efficient, reusable programs. Let us now trace the evolution of object oriented programming in detail Procedural Programming In this paradigm, we divide a problem into sub-problems recursively and then we write a procedure for each sub-problem. Procedures communicate with each other by parameters. In this paradigm, data structures are declared locally or globally. The procedures can contain local data. Pascal and C support this programming approach. For example, if we want to implement a stack, we divide the problem into smaller problems like how to push value in a stack, how to pop a value and how to find whether stack is full or empty. Then we write functions for push, pop, stack empty and stack full and call these functions using its parameters to implement a stack in a program. The stack size is declared in main program using a data structure (may be an array) Modular Programming In this style, the program is divided into modules. Each module will contain all the procedures, which are related to each other and the data on which they act. Modular programming is the other name for data hiding principle. The reason for this name is that the data in a module cannot be accessed by the procedures in another module unless it has been specified that it can be done so. Modular supports this notion. For example, the complete set of operations of a stack including the data structure and functions may reside in a module. The advantages of this paradigm are that we can have different files for a simple program. Each file can be separately compiled and executable file can be made from them. So, if there is any error in one module, the entire program need not be compiled. Only the module in which the error has occurred can be recompiled separately. This will reduce the total compilation time. C enables modular programming by providing provision for including files and separate compilation facilities. The context of module is supported by the class concept of C++. 79

90 Object Oriented Programming through Java Data Abstraction Data Abstraction = Modular programming + Data hiding principle. This concept is supported by C++. In C++, classes can be defined in which the data can be specified as Private. This private data can be accessed only by the member functions of the class. Then, we can define the class as a user defined data type which is the other name of Data Abstraction. So, in this paradigm, we have to decide the types we want and then, we have to provide a full set of operations for each type. For example, in the data structure of stack, the data stored in it cannot be accessed or modified by any other class except the functions of stack class. Then, it can be classified as Data Abstraction Object Oriented Programming When we define data types (user defined data types) we may find similarity among them. Also, when we think of defining a new class, we may find that there is another class which is already processing most of the features of the class, we wish to have. Under such a situation, we can define a class with only additional features and explicitly state that it includes all the features of another class which has been already defined. This concept is known as inheritance. The object oriented programming paradigm is made up of abstraction and inheritance. So, OOP = Data Abstraction + Inheritance. In this paradigm, we have to decide the classes we want; provide a full set of operations for each class and then we have to make commonality explicit by using inheritance. Brief recapitulations of these programming paradigms are given in the following diagram: Procedural programming 0Local and global data 0Use of stack for parameter passing 0Languages that support the paradigm: C, Pascal Modular programming 0Separate compilation of modules 0Data Abstraction =Data hiding principles 0Languages that support this paradigm: ADA, C++ Object-oriented programming 0Data abstraction, Inheritance, Polymorhism 0Languages that support this paradigm: C++, JAVA Other Programming Paradigms 0Functional programming -LISP 0Logic Programming - Prolog 0Concurrent programming 0Distributed component programming, etc. Fig. 6.5 Programming paradigms 80

91 6.5 Objects Here, we will discuss about object and its orientation Object: The Soul of Object Oriented Programming Object oriented Programming and Design is all about objects. Traditionally, code and data are apart. For example, in the C language, units of code are called functions or operations, while units of data are called structures. Functions and structures are not formally connected in C. A C function can operate on more than one type of structure, and more than one function can operate on the same structure. However, it is not true for object oriented programs. In object oriented programming, the data and the operations are merged into a single indivisible unit an object. An object has both state (data) and behaviour (operations on data). In that way, objects are not much different from ordinary physical entities. It is easy to see how a mechanical device embodies both state and behaviour. For example, a simple non moving entity: an ordinary bottle combines state (how full the bottle is? Is it open? How much warm its contents are? With behaviour (the ability to dispense its contents at various flow rates, to be opened or closed to withstand temperatures). It is this resemblance of objects to real things that provides objects much of their power and appeal. They not only can model components of real systems, but also fulfil assigned roles as components in software systems. Therefore, object based programming scheme has many advantages. An object has its well-defined boundary in which it performs its functions while interacting with other objects with its external interface. Objects interact with each other via messages. (Please refer to Fig. 6.6). The concept of object being an entity can be described as, when we refer to some object in real world we know it will be in some state (in time and place). Message for Object 2 Object 1 (Attributes) External Interface via messages Message for Object 3 Message for Object 1 Message Message for Object 1 for Object 3 Object 3 (Attributes) Fig. 6.6 Objects and interfaces Object 2 (Attributes) Message for Object 2 External Interface via messages The Object Orientation Suppose, we want to add two number say, 1 and 2, in an ordinary, non-object oriented computer language like C. We can write this as: a = 1; b = 2; c = a + b; 81

92 Object Oriented Programming through Java The above code implies that takes a number a, which has the value 1, and number b, which has the value 2, and adds them together using the C language s built-in addition capability. Take the result, which happens to be 3 in this case, and places it into the variable called c. Now, here s the same thing expressed in C++, which is a pure object oriented language: a = 1; b = 2; c = a + b; In C++, this says, take the object a which has the value 1, and send it the message +, which includes the argument b which, in turn, has the value 2. Object a, receives this message and performs the action requested to produce a resultant object which in this case has a value 3 and assign this object to object c. The reason is that objects greatly simplify matters when the data get more complex. Suppose we wanted a data type called list, which is a list of names. In C, list would be defined as a structure. struct list <definition of list structure data here> ; list a, b, c; a = Object Oriented ; b = Programming ; Let s try to add these new a and b in the C language: c = a + b; The C compiler will generate an error when it tries to compile this because it does not understand what to do with addition of two strings. C compilers just understand how to add number, but a and b are not numbers. One can do the same thing in C++, but this time, list is defined and implemented as a class called a String. list a, b, c; a = Object-Oriented ; b = Programming ; c = a + b The first three lines simply create list objects a and b from the given strings. The addition may work if the list class was created with a function/method which specifically knows how to handle the message +. For example, the message plus might simply be used for concatenation of two strings. Thus, the value of c may be Object oriented Programming. 6.6 Classes A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations. A class is a group of objects that share common properties and relationships as shown in figure below. 82

93 Object Data Member Function Member Function Object Object Data Member Function Member Function Data Member Function Member Function A typical class declaration would look like: Fig. 6.7 Communication between objects Class item int number; float cost; public: void getdata(int a, float b); void putdata(void); For instance, a software model of a car, a car class, might contain data about the type of car and abilities such as accelerate or decelerate. A class is a programmer defined data type that has data, its members, and abilities, its methods. An object is a particular instance of a class. This is best understood by an analogy with a built-in data type such as int (integer). int x; /* declares x to be a variable of type int.*/ car impala; /* declares impala to be an object of class car.*/ A Complete View of a Class A class is a logical method to organise data and functions in the same structure. They are declared using keyword class, whose functionality is similar to that of the C keyword struct, but with the possibility of including functions with a variety of scope as members, instead of only data. Now let us have a view of a complete class: 83

94 Object Oriented Programming through Java class class_name permission_label_1: member1; permission_label_2: member2;... object_name; In the above example, class_name is a name for the class (user defined type) and the optional field object_name is one, or several, valid object identifiers. The body of the declaration can contain members, that can be either data or function declarations, and optionally permission labels, that can be any of these three keywords: private, public or protected. They make reference to the permission which the following members acquire: Private members of a class are accessible only from other members of their same class or from their friend classes. Protected members are accessible from members of their same class and friend classes, and also from members of their derived classes. Public members are accessible from anywhere the class is visible. If we declare members of a class before including any permission label, the members are considered private, since it is the default permission that the members of a class declared with the class keyword acquire. For example: class crectangle int x, y; public: void set_values (int,int); int area (void); rect; Declares class crectangle and an object called rect of this class (type). This class contains four members: two variables of type int (x and y) in the private section (because private is the default permission) and two functions in the public section: set_values ( ) and area ( ), of which we have only included the prototype. In the previous example, where crectangle was the class name (i.e., the user-defined type), and rect was an object of type crectangle. Now consider the following declaration of a variable: int a; What is the difference between object declaration and variable declaration? After analysis we will find that int is the class name (type) and a is the object name (variable). On successive instructions in the body of the program we can refer to any of the public members of the object rect as if they were normal functions or variables, just by putting the object s name followed by a point and then the class member. For example: rect.set_value (3,4); myarea = rect.area( ); but we will not be able to refer to x or y since they are private members of the class and they could only be referred from other members of that same class. Example 84

95 # include <iostream.h> class crectangle int x, y; public: void set_values(int, int); int area (void) return(x*y); ; void crectangle:: set_values (int a, int b) x = a ; y = b ; int main ( ) crectangle rect; rect.set_values (3, 4 ); cout << area: << rect.area ( ) ; Output: rect area : Scope Operator In the previous example, we have used the operator : : of scope in the definition of set_values ( ). Notice that we have defined the behaviour of function area ( ) within the definition of the crectangle class given its extreme simplicity. Whereas, set_values ( ) has only its prototype declared within the class but its definition is outside. So, in this outside declaration, we must use the operator of scope ::. The scope operator (::) specifies the class to which the member being declared belongs, granting exactly the same scope properties as if it was directly defined within the class. The reason why we have made x and y private members (remember that if nothing else is said all members of a class defined with keyword class have private access) it is because we have already defined a function to introduce those values in the object (set_values( )) and therefore the rest of the program does not have a way to directly access them. One of the greater advantages of a class is that we can declare several different objects from it. For example, if we consider the previous example of class crectangle, we could have declared the object rectb in addition to the object rect. 85

96 Object Oriented Programming through Java Example # include <iostream.h> class crectangle int x, y ; public : void set_values (int, int) ; int area (void) return (x * y) ; ; void crectangle :: set_values (int a, int b) x = a; y = b ; int main ( ) crectangle rect, rectb; rect.set_values (3,4); rectb.set_values (5,6); cout << rect area: << rect.area( ) << endl; cout << rectb area: << rectb.area( ) << endl; Output: rect area: 12, rectb area: 30 The call to rect.area ( ) does not give the same result as the call to rectb.area ( ). This is because each object of class crectangle has its own variables x and y, and its own functions set_value ( ) and area ( ). On that, is based the concept of object and object oriented programming. In that the data and functions are properties of the object, instead of the usual view of objects as function parameters in structured programming. In this concrete case, the class crectangle, of which there are two objects: rect and rectb, each one with its own member variables and member functions Scope of Class and its Members The scope of a class member depends upon its access-specifier (private, public, protected). Scope of private and protected members The private and protected members of a class can be accessed only by the member function of the class. These members cannot be accessed directly by using the object names. In other words, the names of the private and protected members of the class cannot appear except in the body of the class, let us see an example to understand this. 86

97 Example # include <iostream.h> class x private : int a; void fc (void) cout << a; // private data member (a) used by a member function public : int i; void fcc1 (void) cout < 2*i; a=13; // private data member (a) used by a member function ; x Ob1; int main ( ), Ob1.i= 10; Ob1.fcc1( ); Ob1.a = 5; // invalid. a is private data member Ob1.fc( ); //invalid fc( ) is a private member function Scope of public members The scope of public members depends upon the object being used for referencing them. If the referencing object is a global object, then the object of public members is also global and if the referencing object is a local object, then the scope of public members is local. 87

98 Object Oriented Programming through Java Example #include <iostream.h> class x private: int a ; void fc(void) cout << a; public : 12 Object-oriented int i ; void fcc1( void) cout << 2*i; a = 13; fc( ); ; x Ob1; // global object Ob1 int main( ) x Ob2; // local (to main( )) object Ob2 Ob1.i = 10; // Ob1 is global & available to main Ob1.fcc1( ); Ob2.i = 20; // Ob2 is local object available to main( ) Ob2.fcc( ); void func1( ) x Ob3; Ob1.i = 12; // Ob1 is global and hence also available to func1( ) Ob1.fcc1( ); // valid Ob2.i = 25; // invalid Ob2 is not available to func1( ) Ob2.fcc1( ) ; // invalid Ob3.i = 15; // valid. Ob3 is locally available to func1( ) Ob3.fcc1( ); // valid In the above example, Ob1 is a global object, and so the public members of Ob1 can be accessed from any of the functions in the program. Ob2 is a local object, local to function main ( ), and thus, the public members of Ob2 can be accessed only in main ( ) and not in func1 ( ) and not anywhere else. 6.7 Object Oriented Programming Let us study object oriented programming in detail. Whenever we have a problem in hand, we have a very natural tendency to differentiate the problem space and solution space of the problem, i.e., the place where the problem exists and the place where we try to find out answer. When we use computer to solve a problem, then computer is the solution space, i.e., the place where we model that problem and the problem space is the place where the problem that is being solved exists. All programming languages offer some level of abstraction, and the complexity level for its solution space. A problem that we are able to solve by any programming language is directly related to the kind and quality of abstraction done by it. 88

99 What is it that we are abstracting? For example, assembly language is an abstraction of the machine instruction set. Many higher level languages (such as Fortran, BASIC, and C) were abstractions of assembly language. These languages were improvements over assembly language, but their primary underlying abstraction model still required us to think in terms of the structure of the computer rather than the structure of the problem we are trying to solve. It was the job of the programmer to establish the association between the machine and the Problem by proposing the suitable modules, data structures and algorithms. The effort required to perform this mapping is extrinsic to the programming language. Also, this kind of mapping produces programs that are difficult to write and expensive to maintain. Thus, the focus of such programming paradigms is on processing, that is, the algorithms were needed to perform the desired computation on structured data. The programming languages support this paradigm by providing functions and facilities for passing arguments to these functions and returning values from functions. In other words, emphasis was to: decide the structure of data decide which procedures are required (what is needed?) use the best algorithm available (How to achieve it?) For example, A Square root function is: Given a double-precision floating-point argument, it produces the square root. double sqrt (double arg) // code for calculation void f() // function does not return a value double root2 = sqrt (2); // Get and then print the square root Code written within curly brackets express group. They indicate start and end of function bodies. From the point of view of programming, functions are used to create order in a maze of algorithms. The alternative to modelling the machine is to model the problem we are trying to solve. The object oriented approach goes a step further by providing tools for the programmer to represent solution entities with respect to the problem space. This representation is enough to show that the programmer is not constrained to any particular type of problem. We refer to the entities in the problem space and they are allowed to adapt itself to the terminology used for the problem. It may appear to be a more flexible and powerful language abstraction than what we have had before. Thus, the idea behind object oriented programming is to allow us to describe the problem in the terminology of the problem, rather than in terms of the computer where the solution will run. There is still a connection back to the computer, but how? All the programming languages have traditionally divided the world into two parts: data and operations on data. The data is a static entity and can be changed only by the valid operations. The functions that can operate on data have a finite life cycle of its own and can affect the state of data over their lifetime. Such a division is, of course, on the basis the way computers work. The operations or functions have meaning only when they can act on data or modify it. At some point, all programmers, including object oriented programmers must lay out the data structures that their programs will use and define the functions that will act on the data. 89

100 Object Oriented Programming through Java A procedural programming language like C, may offer various kinds of support for organising data and functions. Functions and data structures are the basic elements of procedural design. But object oriented programming tries to model the design of the program as real world philosophy. It groups operations and data into modular units called objects and lets you combine objects into structured networks to form a complete program. In an object oriented programming language, objects and object interactions are the basic elements of design. 6.8 Object Oriented Programming Characteristics The fundamental concept of object oriented programming is that it allows combination of data and functions, methods and procedures which are working on that data, which did not exist in earlier procedure, based programming paradigms. This fundamental unit is called object. An object has a well-defined interface, which is the only way to access the object s data. The data is thus well organised and hidden. Such hidden data is known as encapsulated. The basic terms used in OOPs include data encapsulation and data hiding. Data Procedures/ Functions/ Methods Fig. 6.8 An object An object oriented programming system is composed of multiple objects (see fig. 6.2). When one object needs information from another object, a request is sent asking for specific information, (for example, a report object may need to know what is today s date and will send a request to the date object). These requests are called messages and each object has an interface that manages messages. A primary rule of object oriented programming is that: As the user of an object, we never need to peek inside the box (object). All communications among the objects is done via messages. Messages define the interface to the object. The object that a message is sent to is called the receiver of the message. Everything an object can do is represented by its message interface. So, we need not know anything about what is in the object in order to use it. If we look inside the objects, it may tempt us and we would like to tamper with the details of how the object works. Suppose we have changed the object and later the person who programmed and designed the object in the first place decided to change some of these details, then we may be in trouble. Our software may not be working correctly, but as long as we just deal with objects via their messages, the software is guaranteed to work. Thus, it is important that access to an object is provided only through its messages, while keeping the details hidden. But why should we be concerned about the changes in the object design? Because software engineering experiences have taught us that software do change. A popular saying is that software is not written, it is rewritten. Please remember that some of the costliest mistakes in computer history are because of software that failed when someone tried to change it. The basic characteristics of object oriented programming are as follows: The basic programming entity is the object. An object can be considered to be a variable that stores data and can perform operation on the stored data itself. An object oriented program is a collection of objects for solving a problem. These objects send messages to each other. A message can be equated to a request to call a function of the receiver object. 90

101 Each object has its own memory or data that may be made up of other objects. Thus, object oriented programs are suitable for complex problem solving as they hide the complexity behind the simplicity of objects. Each object can be related to a type, which is its class. An important consideration of a class is that it specifies the message interface that is the messages that can be sent to that type/class of the objects. All object of a particular class can receive the same messages, but may behave differently. This leads to an important conclusion. Let us take an example, a circle object having centre at x=0 and y=0 and a radius of 1 cm. is of the class circle. However, it is also of the type shape. Thus, this object is bound to accept the messages that can be sent to class shape. Similarly, a rectangle object is of type rectangle and also of type shape and will follow messages sent to class shape. Both these objects may be handled using the type shape, but may respond to a message differently on receiving the same message. This is one of the most powerful concepts of object oriented programming language. The concept involves the concepts of inheritance and polymorphism. 6.9 Advantages of Object Oriented Programming The popularity of object oriented programming (OOP) was because of its methodology, which allowed breaking complex and large software programs to simpler, smaller and manageable components. The costs of building large monolithic software were enormous. Moreover, the fundamental things in object oriented programming are objects which model real world objects. Following are the basic advantages of object oriented systems: Modular design: The software built around OOP are modular, because they are built on objects and we know objects are entity in themselves, whose internal working is hidden from other objects and is decoupled from the rest of the program. Simple approach: The objects, model real world entities, which results in simple program structure. Modifiable: Because of its inherent properties of data abstraction and encapsulation, the internal working of objects is hidden from other objects. Thus, any modification made to them should not affect the rest of the system. Extensible: The extension to the existing program for its adaptation to new environment can be done by simply adding few new objects or by adding new features in old classes/types. Flexible: Software built on object oriented programming can be flexible in adapting to different situations because interaction between objects does not affect the internal working of objects. Reusable: Objects once made can be reused in more than one program. Maintainable: Objects are separate entities, which can be maintained separately allowing fixing of bugs or any other change easily. 91

102 Object Oriented Programming through Java Summary Object Oriented Programming, also known as OOP, is a computer science term which is used to describe a computer application that is composed of multiple objects which are connected to each other. An object can be considered a thing that can perform a set of related activities. The set of activities that the object performs defines the object s behaviour. The entire set of data and code of an object can be made a user-defined data type with the help of a class. In other words, objects are variables of the type class. The wrapping up of data and functions into a single unit (called class) is known as encapsulation. Data encapsulation is the most striking feature of a class. Abstraction refers to the act of representing essential features without including the background details or explanations. Inheritance is the process by which objects of one class obtain the properties of objects of another class. It supports the concept of hierarchical classification. Polymorphism is an important OOP concept. Polymorphism, a Greek term, means the ability to take more than one form. The term paradigm describes a set of techniques, methods, theories and standards that together represent a way of thinking for problem solving. The scope of a class member depends upon its access-specifier which are private, public, protected). The popularity of object oriented programming (OOP) was because of its methodology, which allowed breaking complex and large software programs to simpler, smaller and manageable components References Nirosh, 2011, Introduction to Object oriented Programming Concepts and More, [Online] (Updated 25 January 2011). Available at: < aspx#abstract > [Accessed 23 rd March 2011]. Balagurusamy. E., Object Oriented Programming with C++. 3 rd ed., Tata McGraw-Hill Publishing Company Limited. Recommended Reading Lafore.R., Object Oriented Programming in C++, 4 th ed., Pearson Education India. Farrell. J., Object Oriented Programming using C++, 4 th ed., Course Technology, USA; Cengage Learning. Stroustrup. B., A Tour of C++ [Online] (Updated 18January 2002]. Available at: < com/articles/article.aspx?p=25003&seqnum=3> [Accessed 21 March 2011]. 92

103 Self Assessment 1. is defined as an identifiable entity with some characteristic and behaviour. a. Object b. Class c. Data d. Name What are user-defined data types that behave like the built-in types of a programming language? a. Data b. Keywords c. Classes d. Objects is the most striking feature of a class. a. Data encapsulation b. Inheritance c. Polymorphism d. Message passing Which statement is false? a. Inheritance supports the concept of hierarchical classification. b. In C++, the concept of inheritance provides the idea of reusability. c. Inheritance is the process by which objects of one class obtain the properties of objects of another class. d. Each sub-class defines only those features that are unique to it. Which statement is true? a. Polymorphism, an Arabic term, means the ability to take more than one form. b. Inheritance, a Latin term, means the ability to take more than one form. c. Polymorphism, a Greek term, means the ability to take more than one form. d. Polymorphism, a German term, means the ability to take more than one form. Polymorphism is extensively used in inheritance. a. implementing b. calculating c. forcing d. carrying 93

104 Object Oriented Programming through Java Match the following: 1. Object oriented Programming and A. Class Design is all about 2. OOP = B. Modular programming + Data hiding principle 3. Data Abstraction = C. objects 4. It is the blueprint from which the D. Data Abstraction + Inheritance individual objects are created. a. 1-C, 2-D, 3-B, 4-A b. c. d. 1-D, 2-C, 3-B, 4-A 1-B, 2-A, 3-D, 4-A 1-B, 2-C, 3-A, 4-D Class is composed of things. a. two b. c. d. three four five Which of the following is false? a. The data is a static entity and can be changed only by the valid operations. b. c. d. An object oriented programming system is composed of multiple objects. Abstraction refers to the act of representing essential features without including the background details or explanations. A class is simply a representation of a type of program. 10. The wrapping up of data and functions into a single unit (called class) is known as. a. polymorphism b. object c. encapsulation d. inheritance 94

105 Chapter VII Classes and Objects Aim The aim of this chapter is to: introduce the concept of classes explain the method of specifying a class discuss the differences between class and structure Objectives The objectives of this chapter are to: get an overview of static data members explain the concept of constructor describe the process of accessing class members Learning outcome At the end of this chapter, you will be able to: understand the concept of destructors comprehend the pointer to members and static member functions define member functions 95

106 Object Oriented Programming through Java 7.1 Introduction to Classes The basic building blocks of object oriented programming are classes and objects. Class is a A user defined data type with data elements and operations The data members that describe the state of the object. The operations that defines the behaviour of the object. Typically a class is used to introduce a new user defined data type and define abstractions that do not map naturally into predefined or derived data types. Class name Attributes Operations Fig. 7.1 Representation of a class Attributes denote static and dynamic properties. An operation denotes a Attributes service that a class offers to its clients (objects). For example: A Zoo Animal class, an employee class etc. C Structures: It is one of the unique features of the C language is structures. They provide a method for packing together data of different type. A structure is a convenient tool for handling a group of logically related data items. It is a user-defined data type with a template that serves to define its data properties. Once the structure is defined, we can create variables of that type using declarations that are similar to the built-in type declaration. For example: Struct student char name[20]; int roll_number; float total_marks; ; The keyword struct declares student as a new data type that can hold three fields of different data types. These fields are known as structure members or elements. The identifier student, which is referred to as structure name or structure tag, can be used to create variables of type student. 96

107 Differences between class and structure In C++ Structures can have member functions but the default scope of the members of the structure is public. The default scope of the class is private. Structures don t have access restrictions as public, private and protected as in the class. Structures like class can not be inherited. Structures can not have constructors & destructors. 7.2 Specifying a Class A class is a way to bind the data and its associated functions together. It allows the data (and functions) to be hidden, if necessary, from external use. While defining a class, we are creating a new abstract data type that can be treated like any other built-in data type. A class specification has two parts: Class declaration Class function definitions class class_name private: variable declarations; functions declarations; public: variable declarations; functions declarations; ; The keyword class specifies what follows is an abstract data of type class_name. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are grouped under two sections namely, private and public. The class members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. The variables declared inside the class are known as data members and the functions are known as member functions. Only the member functions can have access to the private data members and private functions. However, the public members (both functions and data) can be accessed from outside the class. For example: class item int number; float cost; public: void getdata (int a, float b); void putdata (void); : // ends with semicolon // variables declaration // private by default // functions declaration // using prototype We usually give a class some meaningful name, such as item, this name now becomes a new type identifier that can be used to declare instances of that class type. The class item contains two data members and two functions. The class item contains two data members and two functions members. The data members are private by default while both the functions are public by declaration. The function getdata() can be used to assign values to the member variables number and cost, and putdata() for displaying their values. 97

108 Object Oriented Programming through Java 7.3 Creating Objects Once a class has been declared, we can create variables of that type by using the class name. for example: item x; // memory for x is created creates a variable x of type item. In C++, the class variables are known as objects. Therefore x is called an object of type item. We may also declare more than one object in one statement. For example: item x,y,z; Objects can also be created when a class is defined by placing their names immediately after the closing brace, as we do in the case of structures. Class item x,y,z; Accessing class members The private data of a class can be accessed only through the member functions of that class. The main() cannot contain statements that access number and cost directly. The following is the format for calling a member function: For example, the function call statement x.getdata(100, 75.5) Object-name. function-name (actual-agruments); is valid and assigns the value 100 to number and 75.5 to cost of the object x by implementing getdata() function. The assignments occur in the actual function. 7.4 Defining Member Functions Member functions can be defined in two places: Outside the class definition Inside the class definition Outside the class definition Member functions that are declared inside a class have to be defined separately outside the class. Their definitions are very much lime the normal functions. They should have a function header and a function body. An important difference between a member function and a normal function is that a member function incorporates a membership identify label in the header. This label tells the complier which class the function belongs to. The general form of a member function definition is: return-type class-name :: function-name (argument declaration) function body 98

109 The membership label class-name:: tells the complier that the function function-name belongs to the class classname. That is, the scope of the function is restricted to the class-name specified in the header line. The symbol :: is called the scope resolution operator. Since these functions do not return any value, their return-type is void. The member functions have some special characteristics that are often used in the program development. These characteristics are: Several different classes can use the same function name. the membership label will resolve their scope. Member functions can access the private data of the class. A non-member function cannot do so. A member function can call another member function directly, without using dot operator. Inside the class definition Another method of defining a member function is to replace the function declaration by the actual function definition inside the class. For example, we could define the item class as follows: class item int number; float cost; public: void getdata( int a, float b); // inline function void purdata (void) cout << number << \n ; cout << cost << \n ; ; // declarations When a function is defined inside a class, it is treated as an inline function. Therefore, all the restrictions and limitations that apply to an inline function are also applicable here. Normally, only small functions are defined inside the class definition. 7.5 Static Data Members A static member of a class can be qualified as static. The properties of a static member variable are similar to that of a C static variable. A static member variable has certain special characteristics. These are: It is initialised to zero when the first object of its class is created. No other initialisation is permitted Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created. It is visible only within the class, but its lifetime is the entire program. Static variables are normally used to maintain values common to the entire class. For example, a static data member can be used as a counter that records the occurrences of all the objects. The program below illustrates the use of a static data member. #include >instream> using namespace std; class item static int count; int number; public; 99

110 Object Oriented Programming through Java void getdata (int a) number = a; count ++; void getcount (void) cout << count: ; cout << count << \n ; ; int item :: count; int main () item a, b, c; a.getcount (); b.getcount (); c.getdata (); // count is intialised to zero // display count a.getdata (100); // getting data into object a b.getdata (200); // getting data into object b c.getdata (300); // getting data into object c cout << After reading data << \n ; a.getcount (); // display count b.getcount (); c.getdata (); return o; The output of the program would be: count: 0 count: 0 count: 0 After reading data count: 3 count: 3 count: 3 Note that the type and scope of each static member variable must be defined outside the class definition. This is necessary because the static data members are stored separately rather than a part of an object, they are also known as class variables. 7.6 Static Member Functions Like static member variable, we can also have static member functions. A member function that is declared static has the following properties: A static function can have access to only other static members (functions or variables) declared in the same class. A static member function can be called using the class name (instead of its objects0 as follows: Class-name:: function-name; 100

111 7.6.1 Const Member Functions If a member function does not alter any data in the class, then we may declare it as a const member function as follows: void mul (int, int) const; double get_balance () const; The qualifier const is appended to the function prototypes (in both declaration and definition). The complier will generate an error message if such functions try to alter the data values. 7.7 Pointer to Members It is possible to take the address of a member of a class and assign it to a pointer. The address of a member can be obtained by applying the operator & to a fully operator class member name. A class member pointer can be declared using the operator:: * with the calss name. For example, given the class class a private: int m; public: void show (); ; We can define a pointer to the member m as follows: int A::* ip = &A ::m; The ip pointer created thus acts like a class member in that it must be invoked with a class object. In the statement above, the phrase A::* means pointer-to-member of A class. The phrase & A::m means the address of the member of A class. Remember, the following statement is not valid: int*ip = &m; // won t work This is because m is not simply an int type data. The dereferencing operator->* is used to access a member when we use pointers to both the object and the member. The dereferencing operator.* is used when the object itself is used with the member pointer. Note that *ip is used like a member name. 7.8 Constructor A constructor is a special member function whose task is to initialise the objects of its class. It is special because its name is the same as the class name. The constructor is invoked whenever an object of its associated class is created. It is called constructor because it constructs the values of data members of the class. A constructor is declared and defined as follows: // class with a constructor class integer int m, n; public: 101

112 Object Oriented Programming through Java interger (void);.... ; interger :: integer (void) m=0; n=0; // constructor declared // constructor declared When a class contains a constructor like the one defined above, it is guaranteed that an object created by the class will be initialised automatically. For example, the declaration: integer int1; // object int1 created not only creates the object int1 of type integer but also initialises its data members m and n to zero. A constructor that accepts no parameters is called the default constructor. The default constructor for class A is A::A(). If no such constructor is defined, then the complier supplies a default constructor. Therefore a statement such as: A a; invokes the default constructor of the complier to create the object a. The constructor functions have some special characteristics. These are: They should be declared in the public section They are invoked automatically when the objects are created They do not have return types, not even void and therefore, and they cannot return values. They cannot be inherited, though a derived class can call the base class constructor. Like other C++ functions, they can have default arguments. Constructors cannot be virtual We cannot refer to their addresses Copy Constructor Copy constructor initialises an object by copying the state from another object of the same class. Whenever an object is copied, another object (the copy) is created, this constructor is called copy constructor. If the class of the object being copied is A, the copy constructor s signature is usually A::A (const A&) Default copy constructor provided by the compiler does member wise copy. Usually overridden when an object has data members that are pointers. For example: # include <iostream> using namespace std; class code int id; public: code() code(int a) id = a; code(code & x) id = x.id; //constructor // constructor again // copy in the value 102

113 void display(void) cout << id; ; int main code A(100); code B(A); code C=A; code D; // D is created, not initialised D = A; // copy constructor not called cout << \n id of A: ; A.display(); cout << \n id of B: ; B.display(); cout << \n id of C: ; C.display(); cout << \n id of D: ; D.display(); return 0; The ouput of the program is: id of A: 100 id of B: 100 id of C: 100 id of D: 100 // object A is created and initialised // copy constructor called // copy constructor called again When no copy constructor is defined, the complier supplies its own copy constructor. 7.9 Destructors A destructor, as the name implies, is used to destroy the objects that have been created by a constructor. Like a constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde. For example, the destructor for the class integer can be defined as shown below: -integer () A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the complier upon exit from the program (or block or function as the case may be) to clean up storage that is no longer accessible. It is good a practice to declare destructors in a program since it releases memory space for future use. Whenever new is used to allocate memory in the constructors, we should use delete to free that memory. For example, the matrix class may be defined as follows. matrix :: matrix() for(int i=0; i<d1; i++) delete p[1] delete p; The example below illustrates that the destructor has been invoked implicitly by the complier. #include <iostream> using namespace std; int count = 0; class alpha 103

114 Object Oriented Programming through Java public: alpha() count++; cout << \nno. Of object created << count; alpha() cout << \nno. Of object destroyed <<count; ; int main() cout << \n\nenter MAIN\n ; alpha A1, A2, A3, A4; cout << \n\nenter BLOCK\n ; alphs A5; cout << \n\nenter BLOCK2\n ; alpha A6; cout << \n\nre-enter MAIN\n ; return 0; Output of the program: ENTER MAIN No. of object created 1 No. of object created 2 No. of object created 3 No. of object created 4 ENTER BLOCK1 No. of object created 5 No. of object destroyed 5 ENTER BLOCK 2 No. of object created 5 No. of object destroyed 5 RE-ENTER MAIN No. of object destroyed 4 No. of object destroyed 3 No. of object destroyed 2 No. of object destroyed 1 104

115 Summary The basic building blocks of object oriented programming are classes and objects. Attributes denote static and dynamic properties. An operation denotes a Attributes service that a class offers to its clients (objects). A structure is a convenient tool for handling a group of logically related data items. It is a user-defined data type with a template that serves to define its data properties. The keyword class specifies what follows is an abstract data of type class_name. The class body contains the declaration of variables and functions. These functions and variables are collectively called class members. They are grouped under two sections namely, private and public. Objects can also be created when a class is defined by placing their names immediately after the closing brace, as we do in the case of structures. The private data of a class can be accessed only through the member functions of that class. An important difference between a member function and a normal function is that a member function incorporates a membership identify label in the header A static member variable has certain special characteristics. These are: it is initialised to zero when the first object of its class is created. No other initialisation is permitted. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created, and it is visible only within the class, but its lifetime is the entire program. The type and scope of each static member variable must be defined outside the class definition. If a member function does not alter any data in the class, then we may declare it as a const member function A constructor is a special member function whose task is to initialise the objects of its class. It is special because its name is the same as the class name. References Balaguruswamy, E., Object Oriented Programming with C++. 3 rd ed., Tata McGraw Hill Publishing Company Limited. C++ Objects and Classes. Available at: < [Accessed 15 April 2011]. What is an object? [Online]. Available at: < [Accessed 15 April 2011]. Recommended Reading Balagurusamy, E., Object Oriented Programming with C++. 3 rd ed., Tata McGraw Hill Publishing Company Limited. Lafore, R., Object-Oriented Programming in C++. 4 th ed., Sams. Koffman, E.B., Objects, Abstraction, Data Structures and Design: Using C++. Wiley. 105

116 Object Oriented Programming through Java Self Assessment 1. Which is an important difference between a member function and a normal function? a. Member function incorporates a membership identify label in the header b. Member function incorporates a membership identify label in the body c. Member function incorporates a membership object label in the header d. Member function incorporates a membership structure label in the header Which of the following is false? a. A class is a way to bind the data and its associated functions together. b. The class body contains the declaration of variables and functions. c. The class members that have been declared as public can be accessed only from within the class. d. Once a class has been declared, we can create variables of that type by using the class name. The type and scope of each static member variable must be defined the class definition. a. outside a. inside b. after c. before If a member function does not alter any data in the class, then we may declare it as a: a. const data function b. static member function c. const member function d. const member Which of the following is the function of constructor? a. To initialise the members of its class b. To initialise the objects of its functions c. To declare the objects of its class d. To initialise the objects of its class The data of a class can be accessed only through the member functions of that class. a. public b. private c. static d. dynamic is a user-defined data type with a template that serves to define its data properties. a. Structure b. Class c. Method d. Object 106

117 8. 9. Which of the following is true? a. A destructor takes any argument and returns any value. b. c. d. It is bad a practice to declare destructors in a program since it releases memory space for future use. Copy constructor initialises an object by copying the state from another object of the same class. The constructor is invoked whenever an object of its associated class is destroyed. Like a constructor, the destructor is a member function whose name is the same as the class name but is preceded by a/an. a. member b. c. d. function object tilde 10. A constructor that accepts no parameters is called the constructor. a. copy b. default c. member d. function 107

118 Object Oriented Programming through Java Chapter VIII Operator Overloading Aim The aim of this chapter is to: introduce the concept of operator overloading enlist the rules of operator overloading discuss the type of conversions Objectives The objectives of this chapter are to: highlight loading operators introduce the concept of overloading unary operator explain the process of overloading binary operator Learning outcome At the end of this chapter, you will be able to: understand the concept of overloading operator describe the overloading of unary and binary operators define the rules of overloading operators 108

119 8.1 Introduction to Operator Overloading Operator overloading is one of the many exciting features of C++ language which enhances the extensibility. C++ tries to make the user-defined data types behave in much the same way as the built-in types. C++ has the ability to provide the operators with a special meaning for a data type. The mechanism of giving such special meanings to an operator is known as operator overloading. The law of conservation of complexity says that every application must have an inherent amount of irreducible complexity. Ultimately, complexity isn t actually reduced; it is moved. The advantage of operator overloading is that it moves the complexity from the many users to the few servers. Operator overloading allows existing C++ operators to be redefined so that they work on objects of user defined classes. Operator overloading means giving different meaning to existing operators like +, -, *, / etc. It does not mean a radical change but a slight difference in default behaviour of the operator. Need to change some operators arise when we want to do operations on user defined classes like for example we define a class A. Then we instantiated a and aa from A. Now we want to add a to aa. Normal a + aa does not have any meaning, because a and aa are not derived from standard data types and behaviour of operator + is not defined for our class A. To overcome such problems, C++ has provided us with operator overloading. We can overload the + operator and tell it how to add objects of type class A. In C++, one can overload only following operators: + - * / ^ & ~! = < > + = -= *= %= ^= &= = << >> >>= <<= ==!= <= >= && >*, -> [] () new delete It is not possible to change the precedence of these operators, nor can the expression syntax be changed. For example, it is not possible to define a unary % or a binary! It is not possible to define new operator tokens, but we can use the function call notation when this set of operators is not adequate. 8.2 How to Overload Operators To overload an operator, we must specify its relationship to the class to which the operator is applied. This is done with the help of a special function, called operator function, which describes the task. The general form of an operator function is: return type classname :: operator op(arglist) Function body // task defined Where return type is the type of value returned by the specified operation and op is the operator being overloaded. The op is preceded by the keyword operator. operator.op is the function name. Operator functions are declared in the class using prototypes as follows: vector operator+(vector); vector operator-() friend vector operator+(vector, vector); friend vector operator-(vector); vector operator-(vector &a); int operator ==(vector); friend int operator == (vector, vector) // vector addition // unary minus // vector addition // unary minus //subtraction //comparison // comparison Vector is a data type of class and may represent both, magnitude and direction or a series of points called elements. 109

120 Object Oriented Programming through Java The process of overloading involves the following steps: Create a class that defines the data type that is to be used in the overloading operation. Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function. Define the operator function to implement the required operations. Overloaded functions can be invoked by expressions such as: op x or x op For unary operators and x op y for binary operators, op x (or x op) would be interpreted as: operator op (x) 8.3 Overloading Unary Operators Let us consider the unary minus operator. A minus operator when used as a unary, takes just one operand. We know that this operator changes the sign of an operand when applied to a basic data item. We will see here how to overload this operator so that it can be applied to an object in a much similar way as is applied to an int or float variable. The unary minus when applied to an object should change the sign of each of its data items. Program below shows how the unary minus operator is overloaded. # include <iostream> using namespace tsd; class space int x; int y; int z; public: void getdata(int a, intb, int c); void display(void); void operator-(); ; void space :: getdata( int a, int b, int c) x= a; y = b; z = c; void space :: display(void) cout << x<< ; cout << y<< ; cout << z<< \n ; Void space :: operator-() x = -x; y = -y; z = -z; int main() space S; // overload unary minus 110

121 S.getdata(10, -20, 30); cout << S: ; S.display(); -S; cout << S: ; S.display(); return 0; // activates operator-() function The output of the program is: S: S: Remember, a statement like S2 = -S1; Will not work, because the function operator-() does not return any value. It can work if the function is modified to return an object. 8.4 Overloading Binary Operators The mechanism used for overloading a unary operator is also used for overloading the binary operator. The statement below shows to add two number using a friend function. C = sum(a, B); // functional notation. The functional notation can be replaced by natural looking expressions. C = A+B // arithmetic notation By overloading the + operator using an operator+() function. The program below shows how this is accomplished. # include <iostream> using namespace std; class complex float x; flaot y; public: // real part // imaginary part complex() //constructor 1 complex(float real, float imag) // constructor 2 x = real; y= imag; complex operator+(complex); void display(void); ; complex complex :: operator+(complex c) complex temp; // temporary temp.x= x+c.x; // these are temp.y = y+c.y; // float additions return(temp); void compex ::display(void) 111

122 Object Oriented Programming through Java cout << x<< +j <<y<< \n ; int main(0 complex C1, C2, C3; C1 = complex (2.5, 3.5); C2 = complex (1.6, 2.7); C3 = C1+C2; // invokes constructor1 // invokes constructor2 cout << C1 = ; C1.display(); cout << C2 = ; C2.display(); cout << C3 = ; C3.display(); return0; Output of the program is: C1 = j3.5 C2 = 1.6 +j2.7 C3 = 4.1 = j6.2 Let us have a close look at the function operator+() and see how the operator overloading is implemented. complex complex ::operator+(complex c) complex temp; temp.x = x+c.x; temp.y= y+c.y; return(temp); We should note the following features of this function: It receives only one complex type argument explicitly It returns a complex type value It is a member function of complex The function is expected to add two complex values and return a complex value as a result, but receives only one value as argument. Where does the other value come from? Now let us look at the statement that invokes this function: C3 = C1+ C2; // invokes operator+(0 function We know that a member function can be invoked only by an object of the same class. Here, the object C1 takes the responsibility of invoking the function and C2 plays the role of an argument that is passed to the function. The above invocation statement is equivalent to. C3= C1.operator+(C2); // usual function call syntax Therefore, in the operator+() function, the data members of C1 are accessed directly and the data members of C2 are accessed using the dot operator. Thus, both the objects are available for the function. For example, in the statement: 112

123 temp.x = x + c.x; c.x refers to the object C2 and x refers to the object C1.temp.x is the real part of temp that has been created specially to hold the results of addition of C1 and C2. The function returns the complex temp to be assigned to C Rules for Overloading Operators Although it looks simple to redefine the operators, there are certain restrictions and limitations in overloading them. Some of them are listed below: Only the existing operator can be overloaded. New operators cannot be created. The overloaded operator must have at least one operand that is of under-defined type. We cannot change the basic meaning of an operator for example: the plus(+) cannot be redefined to subtract one value from the other. There are some operators that cannot be overloaded. We cannot use friend functions to overload certain operators. However, member functions can be used to overload them. Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one reference argument. Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a friend function take two explicit arguments. When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class. Binary arithmetic operators such as +,-.*, and / must explicitly return a value. They must not attempt to change their own arguments. 8.6 Types Conversions Size of Size of operator. Membership operator.* Pointer-to-member operator :: Scope resolution operator?: Conditional operator Table 8.1 Operators that cannot be overloaded = Assignment operator ( ) Function call operator [ ] Subscripting operator -> Class member access operator Table 8.2 where a friend cannot be used We know that when constants and variables of different types are mixed in an expression, C applies automatic type conversion to the operands as per certain rules. Similarly, an assignment operation also causes the automatic type conversion. The type of data to the right of an assignment operator is automatically converted to the type of the variable on the left. For example, the statements. int m; float x = ; m = x; convert x to an integer before its value is assigned to m. Thus, the fractional part is truncated. The type conversions are automatic as long as the data types involved are built-in types. 113

124 Object Oriented Programming through Java User-defined data types Consider the following statement that adds two objects and then assigns the result to a third object. v3 = v1 + v2 // v1, v2, v3 are class type objects When the objects are of the same class type, the operations of addition and assignment are carried out smoothly and the complier does not make any complaints. Since the user-defined data types are designed by us to suit our requirements, the complier does not support automatic type conversions for such data types. We must, therefore design the conversion routines by ourselves, if such operations are required. Three types of situations might arise in the data conversion between incompatible types: Basic to class type The conversion from basic type to class type is easy to accomplish. For example, a constructor is used to build a vector object from an int type array. Similarly, we use another constructor to build a string type object from a char* type variable. These are the examples where constructor performs a defacto type conversion from the argument s type to constructor s class type. Consider the following constructor: string :: string(char *a) length = strlen(a); P = new char[length+1] strcpy(p,a); This constructor builds a string type object from a char* type variable a. The variables length and p are data members of the class string. Once this constructor has been defined in the string class, it can be used fro conversion from char* type to string type. Example: string s1, s2; char*name1 = IBM PC ; char* name2 = Apple Computer ; s1 = string(name1); s2 = name2; The statement s1 = string(name1); First converts name1 from char* type to string type and then assigns the string type values to the object s1. The statement s2 = name2; Also does the same job by invoking the constructor implicitly. Class to basic type The constructor functions do not supports conversion of class to basic type. Luckily, C++ allows us to define an overloaded casting operator that could be used to convert a class type to basic type. The general form of an overloaded casting operator function, usually referred to as a conversion function, is: 114

125 operator typename().... (function statements).. This function converts a class type data to typename. For example, the operator double()converts a class object double, the operator int() converts a class type object to type int, and so on. Consider the following conversion function: vector :: operator double() double sum = 0; for(int i=0; i<size; i++) sum = sum + v[i]*v[i]; return sqrt(sum); This functions converts a vector to the corresponding scalar magnitude (magnitude of a vector is given by the square root of the sum of the squares of its components). The operator double() can be used as follows: double length = double(v1); Or double length = V1; where V1 is an object of type vector. Both the statements have exactly the same effect. When the complier encounters a statement that requires the conversion of a class type to a basic type, it quietly calls the casting operator function to do the job. The casting operator function should satisfy the following conditions: It must be a class member It must not specify a return type It must not have any arguments Since it is a member function, it is invoked by the object and therefore, the values used for conversion inside the function belong to the object that invoked the function. This means that the function does not need an argument. One class to another class type There are situations where we would like to convert one class type data to another class type. For example: objx = objy; //objects of different types objx is an object of class X and objy is an object of class Y. The class Y type data is converted to the class X type data and the converted value is assigned to the objx. Since the conversion takes place from class Y to classx, Y is known as the source class and X is known as the destination class. Such conversions between objects of different classes can be carried out by either a constructor or a conversion function. The complier treats them the same way. Our decision to choose the form to use depends upon where we want the type-conversion function to be located in the source class or in the destination class. We know that the casting operator function Operator typename() 115

126 Object Oriented Programming through Java Converts the class object of which it is a member to typename. The typename may be a buit-in type or a user-defined one. In case of conversions between objects, typename refers to the destination class. Therefore, when a class needs to be converted, a casting operator function can be used. The conversion takes place in the source class and the result is given to the destination class object. Now consider a single-argument constructor function, which serves as an instruction for converting the argument s type to the class type of which it is a member. This implies that the argument belongs to the source class and is passed to the destination class for conversion. This makes it necessary that the conversion constructor be placed in the destination class. 116

127 Summary Operator overloading allows existing C++ operators to be redefined so that they work on objects of user defined classes. The advantage of operator overloading is that it moves the complexity from the many users to the few servers. To overload an operator, we must specify its relationship to the class to which the operator is applied. This is done with the help of a special function called operator function, which describes the task. Vector is a data type of class and may represent both magnitude and direction or a series of points called elements. The process of overloading involves the following steps: create a class that defines the data type that is to be used in the overloading operation. Declare the operator function operator op() in the public part of the class. It may be either a member function or a friend function, and define the operator function to implement the required operations. When constants and variables of different types are mixed in an expression, C applies automatic type conversion to the operands as per certain rules. An assignment operation also causes the automatic type conversion. The type of data to the right of an assignment operator is automatically converted to the type of the variable on the left. Three types of situations might arise in the data conversion between incompatible types: conversion from basic type to class type, conversion from class to basic type, and conversion from one class type to another class type. References Balaguruswamy, E., Object Oriented Programming with C++. 3 rd ed., Tata McGraw Hill publishing company limited. Milea, A., Operator overloading [online]. Available at: < operator_overloading.html>. [Accesses on 18 April 2011]. Devarticles.com, Operator overloading in C++ [online]. Available at: < Cplusplus/Operator-Overloading-in-C-plus/>. [Accesses on 18 April 2011]. Recommended Reading Balagurusamy, E., Object Oriented Programming with C++.3 rd ed., Tata McGraw Hill Publishing Company Limited. Loudon, K., C++ Pocket Reference. 1 st ed., O Reilly Media. Hubbard, J., Schaum s Outline of Programming with C++. 2 nd ed., McGraw-Hill. 117

128 Object Oriented Programming through Java Self Assessment 1. Vector is a data type of class and may represent both, magnitude and direction or a series of points called. a. objects b. c. d. functions members elements Which of the following statements is false? a. The constructor functions supports conversion of class to basic type. b. c. d. The conversion from basic type to class type is easy to accomplish. The mechanism used for overloading a unary operator is also used for overloading the binary operator. A minus operator when used as a unary takes just one operand. To overload an operator we must specify what it means in to the class to which the operator is applied. a. addition b. c. d. relationship compatibility support Operator overloading allows existing C++ operators to be redefined so that they work on objects of. a. binary defined classes b. c. d. operator defined classes user defined classes unary defined classes The advantage of operator overloading is that, it moves the from the many users to the few servers. a. complexity b. c. d. simplicity compatibility support Which of the following statement is true? a. C++ allows us to define an overloaded casting operator that could be used to convert a class type to class type. b. c. d. When the objects are of the same class type, the operations of subtraction and assignment are carried out smoothly and the complier does not make any complaints. The type of data to the right of an assignment operator is automatically converted to the type of the variable on the left. C++ has the ability to provide the operators with a special meaning for a object type. 118

129 Binary operators overloaded through a member function take one explicit argument and those which are overloaded through a function take two explicit arguments. a. object b. c. d. friend data class Unary operators, overloaded by means of a member function, take no explicit arguments and return no explicit values, but, those overloaded by means of a friend function, take one argument. a. reference b. c. d. class abstract member When using binary operators overloaded through a member function, the left hand operand must be an object of the. a. member class b. c. d. function class data class relevant class 10. Since the user-defined data types are designed by us to suit our requirements, the complier does not support type conversions for such data types. a. manual b. c. d. automatic relevant explicit 119

130 Object Oriented Programming through Java Chapter IX Inheritance, Multiple Inheritance and Polymorphism Aim The aim of this chapter is to: introduce the concept of inheritance define the derived classes discuss the features of inheritance Objectives The objectives of this chapter are to: introduce polymorphism explain the concept of single inheritance discuss the process of defining the derived class Learning outcome At the end of this chapter, you will be able to: understand the concept of multiple inheritance describe the single inheritance with the public as well as privation derivation define the features of inheritance 120

131 9.1 Introduction to Inheritance Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class. For example, a programmer can create a base class named fruit and define derived classes as mango, orange, banana, etc. Each of these derived classes, (mango, orange, banana, etc.) has all the features of the base class (fruit) with additional attributes or features specific to these newly created derived classes. Mango would have its own defined features, orange would have its own defined features, banana would have its own defined features, etc. Features of inheritance: Reusability: Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed. Saves Time and Effort: The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed. Increases Program Structure which results in greater reliability. 9.2 Defining Derived Classes A derived class can be defined by specifying its relationship with the base class in addition to its own details. The general form of defining a derived class is: Class derived-class-name : visibility-mode base-class-name // // members of derived class // ; The colon indicates that the derived-class-name is derived from the base-class-name. The visibility mode is optional and, if present, may be either private or public. The default visibility-mode is private. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. For Example: class ABC: private XYZ members of ABC ; // private derivation In inheritance, some of the base class data elements and member functions are inherited into the derived class. We can add our own data and member functions and thus extend the functionality of the base class. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very powerful tool for incremental program development. 9.3 Single Inheritance Let us consider a simple example to illustrate inheritance. Program below shows a base class B and a derived class D. The class B contains one private data member, one public data member and three public member functions. The class D contains one private data member and two public member functions. Single inheritance: public # include <iostream> using namespace std; 121

132 Object Oriented Programming through Java class B int a; // private; not inheritable public; int b; // public; ready for inheritance void get_ab(); int get_a(void); void show_a(void); ; class D: public B // public derivation int c; public; void mul(void); void display(void); ; // void B :: get_ab(void) a=5; b=10; int B :: get_a() return a; void B :: show_a() cout << a= << a<< \n ; void D :: mul () c= b*get_a(); void D :: display () cout << a = << get_a() << \n ; cout << b = << b << \n ; cout << c = << c << \n ; // int main () D d; d.get_ab(); d.mul(); d.show_a(); d.display(); d.b = 20; d.mul(); d.display (); 122

133 return 0; Output of the program is: a=5 a=5 b=10 c = 50 a = 5 b = 20 c = 100 The class D is a public derivation of the base class B. Therefore, D inherits all the public members of B and retains their visibility. Thus, a public member of the base class B is also a public member of the derived class D. The private members of B cannot be inherited by D. The class D, in effect, will have more members that what it contains at the time of declaration as shown in the figure given below. Class D Private Section C Public Section b get_ab() Inherited from B B get_a() show_a() mul() display() Fig. 9.1 Adding more members to a class (by public derivation) The program illustrates that the objects of class D have access to all the public members of B. Let us have a look at functions show_a() and mul(): void show_a() cout << a= << a<< \n ; void mul() 123

134 Object Oriented Programming through Java c = b* get_a(); // c=b*a Although the data member is private in B and cannot be inherited, object of D are able to access it through an inherited member function of B. Let us now consider the case of private derivation. class B int a; public: int b; void get_ab(); void get_a(); void show_a(); ; class D: private B int c; public: void mul (); void display (); ; // private derivation The membership of the derived class D is shown in the figure given below. In private derivation, the public members of the base class become private members of the derived class. Therefore, the objects of D can not have direct access to the public member functions of B. 124

135 Class D Private Section C b get_ab() Inherited from B B get_a() show_a() Public Section mul() display() The statements such as Fig. 9.2 Adding more members to a class (by private derivation) d.get_ab(); d.get_a(); d.show_a(); // get_ab is private // so also get_a() // and show_a() will not work. However, these functions can be used inside mul() and display() like the normal functions as shown below: void mul() get_ab(); c = b *get_a(); void display () show_a() cout << b= <<b<< \n << c = <<c<< \n\n ; // outputs value of a 125

136 Object Oriented Programming through Java 9.4 Multiple Inheritances A class can inherit the attributes of two or more classes as shown in the figure given below. This is known as multiple inheritances. Multiple inheritances allow us to combine the features of several existing classes as a starting point for defining new classes. It is like a child inheriting the physical features of one parent and the intelligence of another. B-1 B-2 B-n D Fig. 9.3 Multiple inheritance The syntax of a derived class with multiple base classes is as follows: class D: visibility B-1, visibility B (body of D). ; Where, visibility may be either public or private. The base classes are separated by commas. For example: class P: public M, public N public: void display(void); ; Classes M and N have been specified as follows: class M protected: int m; public : void get_m(int); ; void M :: get_m(int x) m = x; 126

137 class N protected: int n; public: void get_n(int); ; void N :: get_n(int y) n=y; The derived class P, as declared above, would, in effect, contain all the members of M and N in addition to its own members as shown below: class P protected ; public: int m; int n; // from M // from N void get_m(int); void get_n(int); void display(void); // from M // from N // own member The member function display() can be defined as follows: void P:: display(void) cout << m= <<m<< \n ; cout << n= <<n<< \n ; cout << m*n= <<m*n<< \n ; ; The main() function which provides the user-interface may be written as follows: main() Pp; p.get_m(10); p.get_n(20); p.display(); 127

138 Object Oriented Programming through Java Program below shows the entire code illustrating how all the three classes are implemented in multiple inheritance mode. # include <iostream> Using namespace std; class M protected: int m; public: void get_m(int); ; class N protected: int n; public: void get_n(int); ; class P : public M, public N public: void display(void); ; void M :: get_m(int x) m = x; void N :: get_n(int y) n=y ; void P :: display(void) cout << m= << m<< \n ; cout << n= << n<< \n ; cout << m*n = << m*n<< \n ; int main () P p; p.get_m(10); p.get_m(20); p.display(); return 0; 128

139 Output of program is: m = 10 n = 20 m*n = Polymorphism Polymorphism is one of the crucial features of object oriented programming. It simply means one name, multiple forms. The concept of polymorphism is implemented using the overloaded functions and operators. The overloaded member functions are selected for invoking by matching arguments, both, type and number. This information is known to complier at the compile time and, therefore, complier is able to select the appropriate function for a particular call at the compile time itself. This is called early binding or static binding or static linking. Also known as compile time polymorphism, early binding simply means that an object is bound to its function call at compile time. Now let us consider a situation where the function name and prototype is the name in both the base and derived classes, for example, consider the following class definitions: class A int x; public: void show (). ; class B : public A int y; public: ; void shoe () // show () in base class // show () in derived class How do we use the member function show() to print the values of objects of both the classes A and B?. Since the prototype of show() is the same in both the places, the function is not overloaded and therefore static binding does not apply. In such situations, we may use the class resolution operator to specify the class while invoking the functions with the derived class objects. If the appropriate member function is selected while the program is running is known as run time polymorphism. It happens with the mechanism known as virtual function as shown in the figure below. 129

140 Object Oriented Programming through Java Polymorphism Compile time polymorphism Run time polymorphism Function overloading Operator Overloading Virtual functions Fig. 9.4 Polymorphism At run time, when it is known what class objects are under consideration, the appropriate version of the function is invoked. Since the function is linked with a particular class much later than the compilation, this process is termed as late binding. It is also known as dynamic binding because the selection of the appropriate function is done dynamically at run time. 130

141 Summary Inheritance is the process by which new classes called derived classes are created from existing classes called base classes. The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class. Features of inheritance: reusability, saves time and effort, and increases program structure which results in greater reliability. A derived class can be defined by specifying its relationship with the base class in addition to its own details. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. In inheritance, some of the base class data elements and member functions are inherited into the derived class. A class can inherit the attributes of two or more classes, which is known as multiple inheritances. Multiple inheritances allow us to combine the features of several existing classes as a starting point for defining new classes. Polymorphism is one of the crucial features of object oriented programming. It simply means one name, multiple forms. The concept of polymorphism is implemented using the overloaded functions and operators. If the appropriate member function is selected while the program is running is known as run time polymorphism. References Balaguruswamy, E., Object Oriented Programming with C++. 3 rd ed., Tata McGraw Hill publishing company limited. Pitts, R.I., Introduction to Polymorphism in C++ [online]. Available at :< cpp/polymorphism/intro/>. [Accessed on 18 April 2011] Tenoul.com. C++ Object Oriented: Readme First [online]. Available at :< cplusplustutorial.html>. [Accessed on 18 April 2011] Recommended Reading Balagurusamy, E., Object Oriented Programming with C++. 3 rd ed., Tata McGraw Hill Publishing Company Limited. Josuttis, N.M., Object-Oriented Programming in C++. 1 st ed., Wiley Kak, A., Programming with Objects: A Comparative Presentation of Object Oriented Programming with C++ and Java. 1 st ed.,wiley-ieee Press 131

142 Object Oriented Programming through Java Self Assessment 1. The concept of polymorphism is implemented using the functions and operators. a. overridden b. overloaded c. object oriented d. inherited Multiple inheritance allows us to combine the features of several existing classes as a starting point for: a. defining new objects b. c. d. defining new functions defining new classes defining new methods Which of the following statements is FALSE? a. Inheritance helps the code to be reworked in many situations. b. c. d. A derived class can be defined by specifying its relationship with the base class in addition to its own details. Visibility mode specifies whether the features of the base class are privately derived or publicly derived. In inheritance, some of the base class data elements and member functions are inherited into the derived class. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very powerful tool for program development. a. incremental b. c. d. existing object oriented implementing If the appropriate function is selected while the program is running is known as run time polymorphism. a. class b. c. d. object member derived A class can be defined by specifying its relationship with the base class in addition to its own details. a. base b. c. d. derived member function 132

143 is the process by which new classes called derived classes are created from existing classes called base classes a. Inheritance b. c. d. Exception Polymorphism Binding Which of the following statements is true? a. We can delete our own data and member functions and thus extend the functionality of the base class. b. c. d. Inheritance, when used to modify and extend the capabilities of the existing classes, becomes a very dynamic tool for incremental program development. Inheritance decreases program structure which results in greater reliability The derived classes have all the features of the base class and the programmer can choose to add new features specific to the newly created derived class. Early binding simply means that an object is bound to its function call at. a. compile time b. c. d. run time error time development time 10. mode specifies whether the features of the base class are privately derived or publicly derived. a. Dynamic b. Static c. Visibility d. Development 133

144 Object Oriented Programming through Java Application I Inheritance in C++ 1. Program below shows how to calculate volume of cube using the features of inheritance. #include<iostream> using namespace std; class shape private : double length; protected: double breadth; public : ; double len() return(length); shape(double length1,double breadth1) length=length1; breadth=breadth1; //shape() class shape1 public: double height; ; shape1(double height1) height=height1; //shape1() class cuboid : public shape, private shape1 public: cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1) cout << A constructor is called << endl; double volume() 134

145 ; return(height*breadth*len()); double bre() return(breadth); double ht() return(height); int main() cuboid c1(2.4,3.5,6.7); cout << The length of the cuboid is : << c1.len() << endl; cout << The breadth of the cuboid is : << c1.bre() << endl; cout << The height of the cuboid is : << c1.ht() << endl; cout << The volume of the cuboid is : << c1.volume() << endl; return(0); Identify the lines in the program which states that class cuboid inherits class shape as public and class shape1 as private. Identify the lines in the program which declares the constructor of the class cuboid 4. Answers Output of the Program: 5. class cuboid : public shape, private shape1 cuboid(double length1,double breadth1,double height1):shape(length1,breadth1),shape1(height1) cout << A constructor is called << endl; 135

Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune

Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune C++ and Java Board of Studies Prof. H. N. Verma Vice- Chancellor Jaipur National University, Jaipur Dr. Rajendra Takale Prof. and Head Academics SBPIM, Pune Prof. M. K. Ghadoliya Director, School of Distance

More information

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers) Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement

More information

What are the characteristics of Object Oriented programming language?

What are the characteristics of Object Oriented programming language? What are the various elements of OOP? Following are the various elements of OOP:- Class:- A class is a collection of data and the various operations that can be performed on that data. Object- This is

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance Contents Topic 04 - Inheritance I. Classes, Superclasses, and Subclasses - Inheritance Hierarchies Controlling Access to Members (public, no modifier, private, protected) Calling constructors of superclass

More information

COP 3330 Final Exam Review

COP 3330 Final Exam Review COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson Introduction History, Characteristics of Java language Java Language Basics Data types, Variables, Operators and Expressions Anatomy of a Java Program

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING 1. Object Oriented Programming Paradigms 2. Comparison of Programming Paradigms 3. Basic Object Oriented Programming

More information

CS304 Object Oriented Programming Final Term

CS304 Object Oriented Programming Final Term 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes? Generalization (pg 29) Sub-typing

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

OBJECT ORİENTATİON ENCAPSULATİON

OBJECT ORİENTATİON ENCAPSULATİON OBJECT ORİENTATİON Software development can be seen as a modeling activity. The first step in the software development is the modeling of the problem we are trying to solve and building the conceptual

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems Basics of OO Programming with Java/C# Basic Principles of OO Abstraction Encapsulation Modularity Breaking up something into smaller, more manageable pieces Hierarchy Refining through levels of abstraction

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Data Structures using OOP C++ Lecture 3

Data Structures using OOP C++ Lecture 3 References: th 1. E Balagurusamy, Object Oriented Programming with C++, 4 edition, McGraw-Hill 2008. 2. Robert L. Kruse and Alexander J. Ryba, Data Structures and Program Design in C++, Prentice-Hall 2000.

More information

C++ Quick Guide. Advertisements

C++ Quick Guide. Advertisements C++ Quick Guide Advertisements Previous Page Next Page C++ is a statically typed, compiled, general purpose, case sensitive, free form programming language that supports procedural, object oriented, and

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING Wednesady 23 rd March 2016 Afternoon Answer any FOUR questions out of SIX. All

More information

Lecture 6 Introduction to Objects and Classes

Lecture 6 Introduction to Objects and Classes Lecture 6 Introduction to Objects and Classes Outline Basic concepts Recap Computer programs Programming languages Programming paradigms Object oriented paradigm-objects and classes in Java Constructors

More information

C++ & Object Oriented Programming Concepts The procedural programming is the standard approach used in many traditional computer languages such as BASIC, C, FORTRAN and PASCAL. The procedural programming

More information

STRUCTURING OF PROGRAM

STRUCTURING OF PROGRAM Unit III MULTIPLE CHOICE QUESTIONS 1. Which of the following is the functionality of Data Abstraction? (a) Reduce Complexity (c) Parallelism Unit III 3.1 (b) Binds together code and data (d) None of the

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

More information

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

Chapter 1 Getting Started

Chapter 1 Getting Started Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different

More information

1. Write two major differences between Object-oriented programming and procedural programming?

1. Write two major differences between Object-oriented programming and procedural programming? 1. Write two major differences between Object-oriented programming and procedural programming? A procedural program is written as a list of instructions, telling the computer, step-by-step, what to do:

More information

More Java. School of Computer Science University of KwaZulu-Natal. February 10, 2008

More Java. School of Computer Science University of KwaZulu-Natal. February 10, 2008 More Java School of Computer Science University of KwaZulu-Natal February 10, 2008 1 CONTENTS Contents 1 1 Introduction to Objects 7 1.1 What is Object Oriented Programming?......................... 7

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Java Fundamentals (II)

Java Fundamentals (II) Chair of Software Engineering Languages in Depth Series: Java Programming Prof. Dr. Bertrand Meyer Java Fundamentals (II) Marco Piccioni static imports Introduced in 5.0 Imported static members of a class

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects,

Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects, Chapter No. 2 Class modeling CO:-Sketch Class,object models using fundamental relationships Contents 2.1 Object and Class Concepts (12M) Objects, Classes, Class Diagrams Values and Attributes Operations

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

C++ (Non for C Programmer) (BT307) 40 Hours

C++ (Non for C Programmer) (BT307) 40 Hours C++ (Non for C Programmer) (BT307) 40 Hours Overview C++ is undoubtedly one of the most widely used programming language for implementing object-oriented systems. The C++ language is based on the popular

More information

Cpt S 122 Data Structures. Course Review Midterm Exam # 2

Cpt S 122 Data Structures. Course Review Midterm Exam # 2 Cpt S 122 Data Structures Course Review Midterm Exam # 2 Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Midterm Exam 2 When: Monday (11/05) 12:10 pm -1pm

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

CS304 Object Oriented Programming

CS304 Object Oriented Programming 1 CS304 Object Oriented Programming 1. Which of the following is the way to extract common behaviour and attributes from the given classes and make a separate class of those common behaviours and attributes?

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Object-Oriented Programming Paradigm

Object-Oriented Programming Paradigm Object-Oriented Programming Paradigm Sample Courseware Object-Oriented Programming Paradigm Object-oriented programming approach allows programmers to write computer programs by representing elements of

More information

CS260 Intro to Java & Android 03.Java Language Basics

CS260 Intro to Java & Android 03.Java Language Basics 03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance

More information

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 603 203 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E. - Electrical and Electronics Engineering IV SEMESTER CS6456 - OBJECT ORIENTED

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

More information

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U C A N A D I A N I N T E R N A T I O N A L S C H O O L O F H O N G K O N G INHERITANCE & POLYMORPHISM P2 LESSON 12 P2 LESSON 12.1 INTRODUCTION inheritance: OOP allows a programmer to define new classes

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6] 1 Lecture Overview Types 1. Type systems 2. How to think about types 3. The classification of types 4. Type equivalence structural equivalence name equivalence 5. Type compatibility 6. Type inference [Scott,

More information

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CPS122 Lecture: From Python to Java last revised January 4, Objectives: Objectives: CPS122 Lecture: From Python to Java last revised January 4, 2017 1. To introduce the notion of a compiled language 2. To introduce the notions of data type and a statically typed language 3.

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

Inheritance (continued) Inheritance

Inheritance (continued) Inheritance Objectives Chapter 11 Inheritance and Polymorphism Learn about inheritance Learn about subclasses and superclasses Explore how to override the methods of a superclass Examine how constructors of superclasses

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

An Object Oriented Programming with C

An Object Oriented Programming with C An Object Oriented Programming with C By Tanmay Kasbe Dr. Ravi Singh Pippal IDEA PUBLISHING WWW.ideapublishing.in i Publishing-in-support-of, IDEA PUBLISHING Block- 9b, Transit Flats, Hudco Place Extension

More information

Concepts of Programming Languages

Concepts of Programming Languages Concepts of Programming Languages Lecture 10 - Object-Oriented Programming Patrick Donnelly Montana State University Spring 2014 Patrick Donnelly (Montana State University) Concepts of Programming Languages

More information

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Object-Oriented Programming (OOP) Fundamental Principles of OOP Object-Oriented Programming (OOP) O b j e c t O r i e n t e d P r o g r a m m i n g 1 Object-oriented programming is the successor of procedural programming. The problem with procedural programming is

More information

COMP 250 Winter 2011 Reading: Java background January 5, 2011

COMP 250 Winter 2011 Reading: Java background January 5, 2011 Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP

More information

CH. 2 OBJECT-ORIENTED PROGRAMMING

CH. 2 OBJECT-ORIENTED PROGRAMMING CH. 2 OBJECT-ORIENTED PROGRAMMING ACKNOWLEDGEMENT: THESE SLIDES ARE ADAPTED FROM SLIDES PROVIDED WITH DATA STRUCTURES AND ALGORITHMS IN JAVA, GOODRICH, TAMASSIA AND GOLDWASSER (WILEY 2016) OBJECT-ORIENTED

More information

Chapter 4. Defining Classes I

Chapter 4. Defining Classes I Chapter 4 Defining Classes I Introduction Classes are the most important language feature that make object oriented programming (OOP) possible Programming in Java consists of dfii defining a number of

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

Lecture Notes on Programming Languages

Lecture Notes on Programming Languages Lecture Notes on Programming Languages 85 Lecture 09: Support for Object-Oriented Programming This lecture discusses how programming languages support object-oriented programming. Topics to be covered

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 5 Modified by James O Reilly Class and Method Definitions OOP- Object Oriented Programming Big Ideas: Group data and related functions (methods) into Objects (Encapsulation)

More information

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Define and discuss abstract classes Define and discuss abstract methods Introduce polymorphism Much of the information

More information

Inheritance (Outsource: )

Inheritance (Outsource: ) (Outsource: 9-12 9-14) is a way to form new classes using classes that have already been defined. The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes,

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods. Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

WA1278 Introduction to Java Using Eclipse

WA1278 Introduction to Java Using Eclipse Lincoln Land Community College Capital City Training Center 130 West Mason Springfield, IL 62702 217-782-7436 www.llcc.edu/cctc WA1278 Introduction to Java Using Eclipse This course introduces the Java

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

JAVA GUI PROGRAMMING REVISION TOUR III

JAVA GUI PROGRAMMING REVISION TOUR III 1. In java, methods reside in. (a) Function (b) Library (c) Classes (d) Object JAVA GUI PROGRAMMING REVISION TOUR III 2. The number and type of arguments of a method are known as. (a) Parameter list (b)

More information

CS6301 PROGRAMMING AND DATA STRUCTURES II QUESTION BANK UNIT-I 2-marks ) Give some characteristics of procedure-oriented language. Emphasis is on doing things (algorithms). Larger programs are divided

More information

Fundamental Concepts (Principles) of Object Oriented Programming These slides are based on:

Fundamental Concepts (Principles) of Object Oriented Programming These slides are based on: 1 Fundamental Concepts (Principles) of Object Oriented Programming These slides are based on: [1] Timothy A. Budd, Oregon State University, Corvallis, Oregon, [Available] ClickMe, September 2001. 2 What

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

INHERITANCE. Spring 2019

INHERITANCE. Spring 2019 INHERITANCE Spring 2019 INHERITANCE BASICS Inheritance is a technique that allows one class to be derived from another A derived class inherits all of the data and methods from the original class Suppose

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.

More information

Chapter 4 Defining Classes I

Chapter 4 Defining Classes I Chapter 4 Defining Classes I This chapter introduces the idea that students can create their own classes and therefore their own objects. Introduced is the idea of methods and instance variables as the

More information

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1

+2 Volume II OBJECT TECHNOLOGY OBJECTIVE QUESTIONS R.Sreenivasan SanThome HSS, Chennai-4. Chapter -1 Chapter -1 1. Object Oriented programming is a way of problem solving by combining data and operation 2.The group of data and operation are termed as object. 3.An object is a group of related function

More information

Software Design and Analysis for Engineers

Software Design and Analysis for Engineers Software Design and Analysis for Engineers by Dr. Lesley Shannon Email: lshannon@ensc.sfu.ca Course Website: http://www.ensc.sfu.ca/~lshannon/courses/ensc251 Simon Fraser University Slide Set: 2 Date:

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

Module 10 Inheritance, Virtual Functions, and Polymorphism

Module 10 Inheritance, Virtual Functions, and Polymorphism Module 10 Inheritance, Virtual Functions, and Polymorphism Table of Contents CRITICAL SKILL 10.1: Inheritance Fundamentals... 2 CRITICAL SKILL 10.2: Base Class Access Control... 7 CRITICAL SKILL 10.3:

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Forth Meets Smalltalk. A Presentation to SVFIG October 23, 2010 by Douglas B. Hoffman

Forth Meets Smalltalk. A Presentation to SVFIG October 23, 2010 by Douglas B. Hoffman Forth Meets Smalltalk A Presentation to SVFIG October 23, 2010 by Douglas B. Hoffman 1 CONTENTS WHY FMS? NEON HERITAGE SMALLTALK HERITAGE TERMINOLOGY EXAMPLE FMS SYNTAX ACCESSING OVERRIDDEN METHODS THE

More information

Chapter 2 Basic Elements of C++

Chapter 2 Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 2-1 Chapter 2 Basic Elements of C++ At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class Discussion

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Atelier Java - J1. Marwan Burelle.  EPITA Première Année Cycle Ingénieur. marwan.burelle@lse.epita.fr http://wiki-prog.kh405.net Plan 1 2 Plan 3 4 Plan 1 2 3 4 A Bit of History JAVA was created in 1991 by James Gosling of SUN. The first public implementation (v1.0) in 1995.

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction Lecture 13: Object orientation Object oriented programming Introduction, types of OO languages Key concepts: Encapsulation, Inheritance, Dynamic binding & polymorphism Other design issues Smalltalk OO

More information

Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism

Discussion. Type 08/12/2016. Language and Type. Type Checking Subtypes Type and Polymorphism Inheritance and Polymorphism Type Joseph Spring Discussion Languages and Type Type Checking Subtypes Type and Inheritance and 7COM1023 Programming Paradigms 1 2 Type Type denotes the kind of values that programs can manipulate: Simple

More information

PROGRAMMING IN C++ COURSE CONTENT

PROGRAMMING IN C++ COURSE CONTENT PROGRAMMING IN C++ 1 COURSE CONTENT UNIT I PRINCIPLES OF OBJECT ORIENTED PROGRAMMING 2 1.1 Procedure oriented Programming 1.2 Object oriented programming paradigm 1.3 Basic concepts of Object Oriented

More information

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming

More information

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview Introduction to Visual Basic and Visual C++ Introduction to Java Lesson 13 Overview I154-1-A A @ Peter Lo 2010 1 I154-1-A A @ Peter Lo 2010 2 Overview JDK Editions Before you can write and run the simple

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

COMP 250 Fall inheritance Nov. 17, 2017

COMP 250 Fall inheritance Nov. 17, 2017 Inheritance In our daily lives, we classify the many things around us. The world has objects like dogs and cars and food and we are familiar with talking about these objects as classes Dogs are animals

More information