Public

advertisement
Coverage
• Introduction
• Various design issues for OOPs
• C++ and its support for OOP
• Java and its support for OOP
• C# and its support for OOP
• Ruby and its support for OOP
• Python and its support for OOP
• Differences between Java and C++
• Event Handling in Java
• Programming in Object Oriented Languages
OOP
1
Introduction
• Motivation for Object Oriented Languages:
− Encapsulate and reuse programs and data structures
− Inheritance paved way for reusability
− Reuse should provide extension (add new methods or entities),
restriction (derivation restricted to a specific group) and partially
redefined (certain components can be changed)
− Also support polymorphism (with generic data structures) and
abstraction
− Imperative languages does not posses the option of controlling the
use of global variables.
• Object Oriented Programming types:
− OOP is an added feature to the language:
• C++ is called as relative OOP as you can write non-object
oriented programs as well
• Ada supports procedural and data-oriented programming
− Language supports OOP but appearance and basic structure is
similar to that of imperative languages
• Java is based on C++
OOP
2
Introduction
• Object Oriented Programming types:
− Pure OOP languages:
• Supports the following:
− Encapsulation and Information hiding
− Inheritance
− Polymorphism and Dynamic Binding
− All pre-defined types in the language are objects
− All user-defined types are also objects
− Any operation required is handled by sending messages to
objects
− Example: Smalltalk, Eiffel, Ruby
• Different paradigms evolved as procedural (in 1950s to 1970s), dataoriented (in early 1980s) and Object Oriented Programming (in late
1980s)
OOP
3
Introduction
• Abstraction
− Process of making complex stuff simple by providing appropriate
classes to represent those complex entities
− Classes provide abstraction of a thing (object) which contains the
characteristics (attributes) and the behaviour (methods)
− Data Abstraction: encapsulation mechanism to limit both the scope
and the visibility of the data values and functions defined for the
values
− Process Abstraction:
• The way to say what has to be done and not how to do it
• Many sort methods are available in many languages which hide
the implementation of the sorting algorithm
• Abstract Data Types
− Process of creating new objects and hiding its representation from
the program units that use them
− Actual implementation is not made known to the user but users can
use the implementation
− Ex. int in Java – representation is hidden and operations are builtin
OOP
4
Classes and Objects
−
−
−
−
−
−
−
−
−
−
−
Class: Most common abstract data type
Class instances are called as objects
A class that inherits is called a derived class or a subclass
The class from which another class inherits is called as a parent
class or superclass
A class which is within a class is called as inner class
Subprograms that define operations on objects are called as
methods
Calls to methods are called as messages, which are made up of a
method name and destination object
Type checking (for methods) is done at compile-time in staticallytyped languages like Java and checking is done at run-time in
dynamically checked languages like Smalltalk
All the methods of an object are jointly called as message protocol
or message interface.
A class can be made up of two types of variables: class variable
which is one per class and instance variable which is one per
object
Java: class and array are the only two structured types
OOP
5
C++ type checking example
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
using namespace std;
class baseclass
{ public: baseclass() { x = 0; cout << "Base class constructor" << endl;}
private: int x; // private variable
};
class subclass: public baseclass // inheritance
{ public: subclass() { s = 0; cout << "Subclass constructor" << endl;}
private: int s;
};
int main()
{ baseclass e; // calls the base class constructor
subclass s; // calls both base class and sub class constructors
e = (baseclass) s; // is allowed
// e = s; // is allowed and same as previous statement
// s = (subclass) e; // Compilation error - not allowed
}
OOP
6
Encapsulation
• Technique of packaging things together so as to form a well-defined
programming unit
• By packaging things, encapsulation isolates the operational details of a
procedure from its usage
• For example, integer type hides the internal structure of integer and
also does not permit the user from manipulating the bits
• Encapsulation Constructs: Divide large programs into small programs
called as Modules. Subprograms that are logically related are grouped
but separately compiled called as compilation units
• Naming Encapsulation: Divide large programs into many global names
based on logical groupings. Ex. C++ Namespaces and Java Packages
• Encapsulation in C: Interface is placed in a header file.
• Encapsulation in C++: Similar to C. Friend functions can access
private members of the friend class.
• Encapsulation in C#: C# Assembly provides the concept of combining
many files into one single executable file or a dynamic link library.
• Encapsulation in Ruby: Ruby has modules which are used to
encapsulate methods and constants.
OOP
7
Introduction
• Information Hiding:
− Provide the interface to reveal only those that ought to be revealed
− Different from Encapsulation:
• In Encapsulation: packaging makes the information hidden
• In Information Hiding: Only interface is provided and thus hiding
information.
• Constructor
− Memory allocation and initialization is done by constructor
− They do not create instances
− Implicitly called
− Same name as class, with or without parameters
− Constructor without parameters is called as default constructor
− C++: Parameterless constructor is given by default if no constructor
is specified.
• Destructor
− Used to clean or reclaim heap storage
− Implicitly called when the object lifetime ends
− Has the same name as class but with a tilde preceded
− Must be parameterless
OOP
8
Inheritance
• Access controls on encapsulated entities can hide entities
• Code reuse is provided by inheritance
•
•
•
•
•
•
•
•
•
•
•
•
public class test {
public int a;
// instance variables of the class.
public test( ) { … }
// constructor of the class.
// methods specified in the class.
public <type> functionname ( parameters ) { … }
}
int main ( )
{
test y;
// This part is the client of the class as it uses the class.
// y is an object or instance of the class.
}
OOP
9
Inheritance
10
• Single and Multiple Inheritance
− If a subclass inherits from only one parent class, then it uses single
inheritance
− If a subclass inherits from more than one parent class, then it uses
multiple inheritance
− Multiple inheritance might have name collisions
− Classes B and C are derived from the common parent A. Also, class
D has both B and C as parents. This kind of setup is called as
diamond or shared inheritance.
− If a method is defined both in B and C, then which one does class D
derives?
A
C
B
D
A
A
B
C
D
OOP
Polymorphism
11
• When a class hierarchy includes classes that override methods and such
overridden methods are called through a polymorphic variable (or
assignment polymorphism), the binding to the correct method must
be handled dynamically.
• Example: ParentClass sampleobject = new ChildClass();
• Pure Polymorphism:
− A single function can be applied to varied type of arguments
• Inclusion Polymorphism or Overriding:
− Child class has the function with the same signature as that of the
parent class
• Subtype Polymorphism:
− Operations of one type can be applied to another
− Sometimes, Pure polymorphism is also called as Subtype
polymorphism.
− Alternatively, Inclusion polymorphism is also called as Subtype
polymorphism
OOP
Polymorphism
Pure Polymorphism
12
Inclusion Polymorphism
import java.util.*;
class ParentClass
{ void fn(){
class baseclass{
public void multOverride(int i, int j){
int n = i*j; System.out.println(n); } }
System.out.println("ParentClass.fn"); } }
class Overriding extends baseclass {
class ChildClass extends ParentClass
// same signature as base class but
{ void fn(){
different implementation
System.out.println("ChildClass.fn"); } }
public void multOverride(int i, int j){
public class PurePolymorphism
int n = i*j*2; // multiple i and j by
{ public static void function(ParentClass x) 2.
{ System.out.println("function");
System.out.println(n); } }
x.fn(); }
public class OverloadingOverriding{
public static void main(String[] args)
public static void main(String[] args){
{ ParentClass test = new ChildClass();
Overriding override = new
function(test); test.fn(); } }
Overriding();
override.multOverride(1,2); } }
OOP
Polymorphism
• Adhoc Polymorphism or overloading
− Different functions are denoted with same name but with different
signatures
• Parametric Polymorphism
− Type of the parameters is unspecified in the declaration
− Ex. Ada Generic, C++ Template
−
−
−
−
−
−
−
−
−
−
−
#include <iostream>
using namespace std;
template <typename T>
T max(T x, T y) { return x > y ? x : y; }
int main()
{
int i = 1 ,j = 2; cout << max(i,j) << endl; // Prints 2
float a = 2.0, b = 3.0; cout << max(a,b) << endl; // Prints 3
string s = "abc", t = "def"; cout << max(s,t) << endl; // Prints def
return 0;
}
OOP
13
Polymorphism
Subtype Polymorphism
import java.util.*;
abstract class ParentClass
{ abstract void fn(); }
class ChildClass1 extends ParentClass
{ void fn(){
System.out.println("ChildClass1.fn"); }
}
class ChildClass2 extends ParentClass
{ void fn(){
System.out.println("ChildClass2.fn"); }
}
public class SubtypePolymorphism
{ public static void main(String[] args)
{ ParentClass test1 = new ChildClass1();
test1.fn();
ParentClass test2 = new ChildClass2();
test2.fn(); } }
14
Adhoc Polymorphism
class Overloading {
// Methods with same name but with
different signatures
public void addOverload(int i, int j){
int n = i+j; System.out.println(n); }
public void addOverload(int i, int j,
int k){
int n = i+j+k; System.out.println(n);
}}
public class OverloadingOverriding{
public static void main(String[] args){
Overloading overload = new
Overloading();
overload.addOverload(1,2);
overload.addOverload(1,2,3); } }
OOP
Introduction
• Type checking and Polymorphism
− Type checking between formal and actual parameters is
vital
− Dynamic error checking is costly and delays error
detection
• Abstract Method and Class
− An abstract method is one that does not include the
implementation of the method but has the protocol
(definition)
− An abstract class is one that includes at least one
abstract method. It cannot be instantiated
− Abstract methods are sometimes called deferred and a
class that has a deferred method is called a deferred
class. It is called so because the implementation is
deferred until a subclass defines it
OOP
15
Introduction
• Various Class types:
− Data Manager Classes: The data managed is either
called as data or state. Data Manager Classes maintain
data or state information.
− Data Sinks or Data Sources Classes: Generates data
like a random number generator but does not hold the
data for any period of time.
− View or Observer Classes: Displays the information on
an output device such as a terminal screen.
− Facilitator or Helper Classes: Used to do complex
tasks but has very minimal or no state information
themselves.
OOP
16
Exceptions
17
• An Exception is any unexpected or infrequent event which is raised and
thrown, during runtime.
• An execution handler is a procedure or code sequence that is designed
to be executed when a particular exception is raised. An exception
handler is said to handle or catch an exception.
• Exception handler might cause the program to be continued (called as
resumption model) or terminated (called as termination model).
• Resumption model: the process of returning back through function
calls to the caller during the search for a handler is called call
unwinding or stack unwinding
• Generally, languages support termination model
• C language: No exception handling
OOP
Exceptions
• Synchronous exception is caused by errors that the programs can
definitely catch
• Asynchronous exception is something that could happen any time and
might be due to failure of hardware devices or memory allocation or
communication problems
• Issues related to Exceptions:
− Presence or absence of predefined exceptions
− Scope of user-defined exceptions
− Passing of control to the handler: Termination or resumption model
OOP
18
Object and Class representations
• In Software engineering, class diagram and object diagram are used to
represent the information about classes and objects
• Class diagram is used to provide information about the class; object
diagram is used to indicate information about objects
• This representation is done in Unified Modeling Language (UML)
• Class/Objects representation:
− Represented as box with three rows
− class name, attributes (member variables) and the operations
(member functions) associated with the class
• Visibility of the class
− Public is represented as +, Protected as #, Private as -,Package as ~
OOP
19
Object and Class representations
• Association in class diagram
− Association indicates “owns a” relationship.
− Company offers trainings. Company and Training are classes.
− One company (1) can conduct many (1..*) trainings
Company
Training
1
1..*
• Aggregation and Composition
− Aggregation indicates “has a” relationship
• If container (Toyoto) is destroyed, the contents (Car) are not
destroyed
− Composition indicates “owns a” relationship
• if the container (Circle) is destroyed, the contents (Point) are
also destroyed
OOP
20
Object and Class representations
• Generalization
− Indicates “is a” relationship
− subclass implementing Base class
BaseClass
SubClass1
SubClass2
− Inheriting an implementation
Interface
SubClass1
SubClass2
OOP
21
Object and Class representations
• Dependency
− Indicates a weak relationship between two or more classes
− In this example, any change in Package 2 will affect Package 1.
Package1
Package2
• Object data representation
− Class instance record (CIR) is used along with virtual method table
(or virtual function table or dispatch table or vtable) to represent a
class in the memory
− CIR contains the necessary member variables and a pointer to the
vtable (called as vpointer or virtual table pointer) that contains the
member functions that ought to be dynamically bound
OOP
22
Object and Class representations (C++)
23
• class A
• { public: void fn1() { }
•
virtual void fn2() {}
•
int avar; };
• class B : public A
• { public: void fn2() {}
vtable of class A
Pointer to vtable of
class A
A::fn2
int avar
• int bvar; };
• int main()
int bvar
• { B *b1 = new B(); }
• vtable contains only the member variables and pointers to
other vtables. The non-virtual functions are not stored in
the vtable
OOP
Object and Class representations (Java)
24
• class A
• { public int avar;
•
public void fn1() { }
•
public void fn2() { }
• };
• class B extends A
• { public void fn2() {}
•
public int bvar; };
CIR of class B
vtable of class B
Pointer to vtable of
class B
A’s fn1
int avar
B’s fn2
int bvar
• public Sample
• { public static void main(String[] args)
•
{ B b1 = new B(); } }
• In Java, all methods are dynamically bounded and thus all methods
exist in the vtable
OOP
Design Issues in OOP
25
• Pure object-oriented language: Everything should be considered as an
object (including primitive data types like integer)
• Everything as object slows the operation on simple objects.
− Use imperative typing system and add objects to it
− Include imperative style typing system for primitive data types with
everything else as objects
• Subclasses as subtypes
− “is-a” relationship holds between a parent class object and an
object of the subclass
− Sometimes, subclass might add new methods or methods with
different signature
− If there exists a "is-a" relationship between the parent and the
subclass, then the subclass is called as subtype
Base Class
Shape
Is-A Link
OOP
Sub Class
Circle
Design Issues in OOP
• Allocation and de-allocation of objects
− Can be done on heap or run-time stack
− Object allocation on stack
• Limitation on the expandability of the element
• With p1 as variable for parent class and c1 as variable for
subclass, if space is allocated for p1 and we assign p1 = c1,
problem persists if c1 has more elements than p1
− Object allocation on heap
• How about de-allocation: Implicit or explicit?
• If only the interface of the parent class is visible to the subclass, it is
called as interface inheritance
• If the subclass inherits the exact behaviour of the parent by default, it
is called as implementation inheritance.
• Dynamic (Late Binding) and Static binding:
− Dynamic binding should be handled at run time
− Using dynamic binding always makes the process slower and thus
inefficient
OOP
26
Copying of Assignment Values
•
•
In assignment: Right hand side expression is evaluated and the result
is copied to the left hand side
Two ways to do assignment:
− Copy semantics (also called as value semantics) means the value
of the particular element is copied and not the pointer.
− Reference semantics (also called as pointer-copy semantics)
means that the pointer is copied and not the values
•
Java like Smalltalk uses reference semantics for arrays and objects.
But for primitive data types, Java uses copy semantics.
•
C and C++ languages support reference semantics for arrays. C++
supports both copy and reference semantics for objects
−
−
−
−
#include <stdio.h>
int main() { int array1[3] = {1,2,3}; int array2[3] = {2,3,4};
array1 = array2; // compilation error.
return 0; }
OOP
27
Copying of Assignment Values
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
#include <iostream>
Output:
using namespace std;
// reference semantics
class A { public: int i;
Address of RS1:0x10a2dc8
Address of RS2:0x10a2dc8
A() { i=0; } A(int j) { i=j; }
Value at RS1:10
};
Value at RS2:10
// Both RS1 and RS2 remains the same
int main() {
address.
A *rs1 = new A(10); A *rs2;
// copy semantics
// reference semantics
Address of CS1:0x22cc98
Address of CS2:0x22cc94
rs2=rs1;
Value in CS1:10
// print RS1, RS2 addresses and values
Value in CS2:10
delete rs2; A cs1(10); A cs2;
//copy semantics
cs2 = cs1;
// print RS1, RS2 addresses and values
return 0; }
OOP
28
Copy semantics in Java (using clone())
•
class Example { public static void main(String[] args)
•
{ int[] x = {1,2,3}; int[] y = x; x[0] = 40;
•
System.out.println("y[0] = " + y[0]); // Prints 40
•
System.out.println("x[1] = " + x[1]); // Prints 2
•
System.out.println("y[1] = " + y[1]); // Prints 2
•
int[] y1 = (int[])x. clone();
•
System.out.println("y1[0] = " + y1[0]); // Prints 40
•
System.out.println("x[0] = " + x[0]); // Prints 40
•
y1[1] = 10; // this change impacts only y1 and not x or y
•
System.out.println("y[1]= " + y[1]); // Prints 2
•
System.out.println("x[1]= " + x[1]); // Prints 2
•
System.out.println("y1[1] = " + y1[1]); // Prints 10
•
}}
OOP
29
C++ and its support for OOP
•
Main function returns an integer but we indicate the return type as
void to indicate no return value
•
Destructor procedure (represented by the same class name preceded
by a tilde) is called automatically just before the object disappears
•
C++ uses mixed type system because it includes the type system of C
and adds classes to it
•
C++ supports both object oriented and imperative type of coding and
thus uses static binding by default
•
To use dynamic binding, keyword virtual has to be used
•
Objects are created on stack as well as on heap
•
new operator:
−
−
Used to dynamically allocate an object
Used to take the input parameters and passes them into the
object constructor, and returns a pointer to the memory location
of the created object
OOP
30
C++ and its support for OOP
•
Creating objects on the stack:
−
•
classname classname(arguments);
Creating objects on the heap:
−
−
classname* objectname = new classname(arguments);
delete objectname; // delete the object
•
If an object of a subclass that has extra attributes is copied onto an
object of the super class, then only those attributes defined in super
class are copied. This process of not copying everything is called as
slicing.
•
Accessing Members of a class:
−
−
Statically allocated object: dot operator “.”
Dynamically allocated object: arrow operator “->”
OOP
31
C++ and its support for OOP
•
Inheritance
−
−
Access Controls: private or public or protected
• Private members are visible only to the class and the friends.
• Public members are visible in subclasses and clients.
• Protected members are visible in the class and in the
subclasses but not in the clients
Subclasssing uses access controls like private or public
• Private derivation means inherited public and protected
members are private in the subclasses.
• Public derivation means public and protected members are
also public and protected in subclasses
• Default is private for classes and public for struct
OOP
32
C++ and its support for OOP
•
Subtyping
−
−
•
Called as interface inheritance
If X inherits from Y, then C++ type checker will allow X objects to
be assigned to Y class pointers
Multiple Inheritance
−
−
Name conflicts are resolved using scope resolution operator
Name clash is possible if classes A and B have the same name and
Class C inherits from these two classes
− Implicit resolution: The language resolves the existing
name conflict with an arbitrary rule.
− Explicit resolution: The programmer must explicitly
specify how to resolve the name conflict in his code.
− Disallow name clashes: Name clashes are not allowed in
programs
OOP
33
C++ and its support for OOP
•
34
Dynamic Binding
−
−
−
Using keyword virtual, dynamic binding is implied. This is because
compiler cannot always determine which version of the function
is being called
To declare a function virtual, precede its prototype with the
keyword virtual. Any class with an abstract method is called as an
abstract class, but those which have only pure virtual methods
and no data are called as pure abstract class.
A pure virtual function is one without any definition. A class that
has at least one pure virtual function is an abstract class
• class abc {
• public:
− virtual double xyz () = 0; // pure virtual
− …
• };
OOP
C++ and its support for OOP
•
Friend classes and functions
−
−
−
•
•
•
•
•
•
•
•
•
•
Friend mechanism allows the programmer to bypass class
restrictions
class A1 { friend class A2; };
Class A1 declares class A2 as its friend. By doing this, member
functions of class A2 are permitted to directly read or modify the
private data entities of class A1
#include <iostream>
using namespace std;
class mainclass { int private_data; friend class friendclass;
public: // does not matter if it is private also
mainclass() { private_data = 10; } };
class friendclass { public: int addition(int a) {
mainclass mainclassobj; // access private variable of the mainclass
return mainclassobj.private_data + a;
} };
int main() { friendclass friendclassobj;
cout << "Result: "<< friendclassobj.addition(5)<< endl; }
OOP
35
C++ and its support for OOP
•
Encapsulation
−
−
−
−
−
−
−
−
−
−
−
−
−
−
Using C++ Namespaces
#include <iostream>
using namespace std;
namespace one { int a = 10;}
namespace two { double a = 10.1234;}
int main () { using namespace one;
cout << a << endl; // access a in one
cout << two::a << endl; // access a in two
using one::a; cout << a << endl; // access a in one
// scope for using a namespace with brackets
{ using namespace one; cout << a << endl; }
{ using namespace two; cout << a << endl; }
return 0;
}
OOP
36
C++ and its support for OOP
•
Templates
−
−
−
−
−
−
−
−
−
−
−
−
−
Used to provide overloaded functions
#include <iostream> // iostream.h is depreciated
using namespace std; // needed for cout to work
template <typename T>
T min1(T x, T y) // min is an inbuilt name and thus use min1
{ return x < y ? x : y; }
int main()
{
// Here the min1 function is being called with different data
types
int i = 1 ,j = 2; cout << min1(i,j) << endl;
float a = 2.0, b = 3.0; cout << min1(a,b) << endl;
string s = "abc", t = "def"; cout << min1(s,t) << endl;
return 0; }
OOP
37
C++ and its support for OOP
•
Exceptions
−
−
Does not have predefined exception types
Standard library modules provide exceptions and exception
mechanisms.
−
−
−
−
−
−
−
−
−
−
−
−
−
#include <iostream>
#include <vector>
#include <exception>
#include <stdexcept> // out_of_range exception
using namespace std;
int main( ) { char array[] = {'a', 'b', 'c', 'd'};
// no error is caught and just a random value is printed.
try { cout << array[10000];
} catch(std::out_of_range& e) {cerr << e.what( ) << '\n';}
vector<char> v; v.push_back('a'); v.push_back('b'); v.push_back('c');
// Runtime error: vector :: _M_range_check occurs
try { cout << v.at(10000) << '\n';
} catch(std::out_of_range& e) { cerr << e.what( ) << '\n';} }
OOP
38
Java and its support for OOP
39
•
All data are objects except the primitive types
•
All primitive types have wrapper classes that store one data value
(wrapper Integer for the primitive type int). Wrapper classes are used
to wrap primitive values and make them as objects
•
As all methods in wrapper class are static, we could use them without
creating an instance
•
import java.util.*;
•
public class Wrapper{ public static void main(String argv[]){
•
Vector v = new Vector();
•
// add needs the parameter to be an object
•
// wrapper class converts the integer into an object
•
v.add(new Integer(100)); v.add(new Integer(200));
•
for(int i = 0; i < v.size(); i++){
•
System.out.println(ival);
Integer ival =(Integer) v.get(i);
} }
OOP
Java and its support for OOP
•
All objects are allocated as heap-dynamic and referenced through
reference variables
•
Garbage collector runs as a thread (low priority process)
•
Explicit calling of garbage collector in Java could be done using
System.gc()
•
Invoking or automatic running of garbage collector calls a special
method called finalize in Java, which acts like a destructor
•
Keyword super: Used to invoke the overridden method
•
class A { void fn(){ System.out.println("a.fn"); } }
•
class B extends A { void fn(){ System.out.println("b.fn"); super.fn();} }
•
public class Binding {
•
public static void main(String[] args) { B a = new B();
•
•
a.fn(); // prints b.fn and a.fn }
}
OOP
40
Java and its support for OOP
•
Access Modifiers
−
•
Substring Method
−
−
•
Static [shared by all instances of the class], Public, Protected
and Private
Its of the form string_name.substring(begin,end)
Returns all the characters from the location "begin" till the
location just before the "end" argument, i.e., it does not include
the "end" argument
Static Field
−
−
−
−
−
−
−
A field declared as static is one per whole class
static { … } // This is called as static initialization block
public class StaticTest
{ static int foo = 123; static { foo = 99; System.out.println(foo);}
public static void main(String argv[]){
System.out.println(foo); } }
This program prints 99 twice.
OOP
41
Java and its support for OOP
•
Inheritance
−
−
−
−
−
−
−
−
−
−
−
Uses extends keyword
Only single inheritance is allowed
Multiple inheritance can be done only with interfaces (abstract
methods)
All of the methods in an interface must be abstract; only constant
(final variables) may be concretely declared in an interface
Interface will not have a constructor
When an interface is extended, then all methods present in the
interface should be implemented
class A { final void fn(){ System.out.println("a.fn"); } }
class B extends A { // Compilation error – B cannot override fn() in A
void fn(){ System.out.println("b.fn"); } }
final class C { } // Compilation error – cannot inherit from final C
class D extends C { }
OOP
42
Java and its support for OOP
•
The final modifier
−
•
The abstract modifier
−
−
−
•
Class indicated as final cannot be extended and thus cannot be a
parent class
An abstract class is declared with the keyword abstract and may
or may not contain abstract methods
If a class contains an abstract method, then the class must be
declared as abstract class
The difference between interfaces and abstract classes is that
abstract class can contain fields that are not static and final and
also can contain implementation methods
Dynamic Binding
−
−
All messages are dynamically bound to methods, unless the
method is final (means it cannot be overridden; therefore,
dynamic binding serves no purpose)
If a method is specified as private or static, then it will disallow
overriding and thus will be statically bound
OOP
43
Java and its support for OOP
OOP
44
Java and its support for OOP
•
Overloading
−
−
−
•
Can have different signatures for a single method
Handled at compile time by matching the arguments
if the method that is invoked is an instance method, then
checking can be done only at runtime, using dynamic method
lookup
Encapsulation
−
−
−
−
−
Provided using classes and packages
Package can contain more than one class definition
Package scope makes the entities visible throughout the package
it is defined. But, not visible to subclass in other packages
Every class in a package is a friend to the package scope entities
elsewhere in the package. So, it is like friends in C++
package packagename;
import packagename.classname;
−
import directoryname.subdirectoryname.packagename.classname;
−
OOP
45
Java and its support for OOP
•
•
•
•
46
In java.lang.String.substring(), java.lang stands for the packagename
and String stands for the classname and substring() stands for the
methodname
Major difference between Java and C++ is that in Java all method
dispatching is done at run time, usually referred to as virtual
methods.
− Vector v; … System.out.print(v.toString());
Run-time type of v is unknown; it could be a Vector, a Stack, or some
other subclass of Vector. So the actual toString method invoked
depends on run-time type of v
Exceptions: try .. catch .. finally
−
−
−
−
−
−
class Exceptions { public static void main(String[] args)
{ System.out.println("Array Bound Test");
// Assign array of 10 elements.
int [] array = new int[10] ; try { array[20] = 1; }
catch (ArrayIndexOutOfBoundsException e)
{ System.out.println("Out of Array Bounds error."); } } }
OOP
C# and its support for OOP
•
•
•
•
•
•
•
•
C# is based on C++ and Java
Access modifiers: internal, protected internal
− Types or methods indicated as internal are accessible to any files
within the same assembly.
− The modifier protected internal, includes the features of both
protected and internal.
Class instances are heap dynamic
Default constructor is implicitly added, if there is no explicit
constructor
Structs are lightweight classes which has no inheritance support
To access data members, accessor methods (getter and setter) are
used
Files can be grouped using C# Assembly
Inheritance in C# is similar to that of Java, except that the syntax is
similar to that of C++
− public class Weather : forecast { … }
OOP
47
C# and its support for OOP
•
public class AcademicYear {
•
public int Days { // Days is a property
•
get { return days; }
•
set { days = value; }
•
}
•
private int days;
•
}
•
AcademicYear ay = new AcademicYear();
•
int holidays, holidaysnow; ay.Days = holidays; holidaysnow = ay.Days;
•
Dynamic binding requires virtual and override keywords
−
−
public class forecast { public virtual readvalue () { … } }
public class Weather : forecast { public override readvalue () { … }
}
OOP
48
C# and its support for OOP
•
•
Access Modifiers
− By default, class methods and fields are considered private
− Namespaces in C# are always public
− Classes and interfaces defined are either public or internal
− Classes are by default considered to be internal
− There is no access modifier for enumerations, they are by default
public.
Exceptions
− Similar to Java and C++
− Using of catch is optional and thus finally can be used alone
− User-defined exceptions can also be specified
− An exception can be thrown so as to be caught from another class
OOP
49
C# and its support for OOP
•
public static void Main()
•
{ int x = 0; int division = 0;
•
try
•
{ division = 100/x; }
•
// can be used to catch all exceptions
•
catch { Console.WriteLine("Exception"); }
•
finally
•
{
•
Console.WriteLine("Finally Block");
•
}
•
}
// Prints the finally block
OOP
50
C# and C++
•
C++ and C# supports polymorphism and inheritance
•
C# uses namespaces instead of C++ headers
•
Java: All methods are considered to be virtual by default
•
C#: Methods need to be specified as abstract, which is equivalent to
pure virtual in C++
•
C# has destructor but is converted to Finalize() method which chains
up to the base class
•
Destructor cannot be explicitly called in C#
−
−
−
−
−
protected override void Finalize()
{
try { .. }
finally { base.Finalize(); }
}
OOP
51
C# and C++
•
•
•
•
•
•
•
If some unmanaged resources need to be freed, then the IDisposable
interface needs to be implemented and the method named Dispose()
should be used to free the resources
Boxing and unboxing is the process of treating value types like
integers as reference types (objects)
Boxing is implicit in C# but unboxing must be done explicitly.
− int i = 12345
− object o = i; //Boxing
− int j = (int) o; // unboxing (must be handled explicitly)
− Console.WriteLine("j: {0}", j);
Boolean variable in C# do not equate to integer variables
Structs do support methods, fields, operators but without inheritance
or destructors
Classes in C++ ends with a semi-colon but not so in C#
C# does not support multiple inheritance but supports multiple
interfaces like in Java
OOP
52
Ruby and its support for OOP
•
Every data type is considered as an object
•
Access modifiers: public, protected, private
− Public methods can be accessed from everywhere
− Private methods can be accessed only when they are called
without an explicit receiver
− Protected methods can be accessed by the same class or its
descendant class instances
•
Variable Types
− Instance variables are preceded with @ sign
− Instance variables are accessed using getter and setter methods
or metaprogramming
• class Student
•
attr_reader :name, :id
•
def initialize(name, id)
•
@name, @id = name, id
•
end
• end
OOP
53
Ruby and its support for OOP
•
Only one constructor (with or without parameters) is allowed per
class
•
Local Variables can start with small alphabets or underscore
−
Unlike global or instance variables, local variables are not given a
nil value before initialization
•
Global variables are preceded with $ sign
•
Class variables are preceded with @@ sign
•
Constants start with upper case characters and are accessible outside
the class
•
self refers to the currently executing object
•
nil refers to the meaningless value that is assigned to uninitialized
variables
OOP
54
Ruby and its support for OOP
•
Method Access
−
−
Uses :: or include
Methods defined inside a class are private by default
OOP
55
Ruby and its support for OOP
•
Singleton Methods
−
−
Methods can behave differently for different instances of a single
class
Called as pre-object methods
OOP
56
Ruby and its support for OOP
•
Inheritance
−
−
Does not support multiple inheritance
Modules can be imported using mixins. Mixin is a class that could
be inherited by other classes but cannot work alone
OOP
57
Ruby and its support for OOP
•
Exception Handling
−
−
−
•
Handled using raise, rescue and ensure
ensure is used to handle the necessary cleanups that ought to be
done once the task is done
Exceptions are said to be raised when they occur within the
execution of a program
Metaprogramming: Programs can be written and modified at runtime
without being recompiled. Programmers can modify or add methods
to standard libraries during runtime
OOP
58
Python and its support for OOP
•
No specific variable type in Python
•
Variables need not be declared
•
Global variables are allowed but discouraged
•
Inheritance
− Brackets are used to indicate inheritance
− Support Multiple Inheritance
•
Access Modifiers
− A method or an attribute can be made private by preceding it
with two underscores
OOP
59
Python and its support for OOP
OOP
60
Python and its support for OOP
OOP
61
Java and C++
•
C++ has destructor but there is no destructor in Java
− Java has finalize() method which is called by garbage collector.
− finalize() cannot be explicitly invoked but can be invoked via
calling garbage collector using System.gc().
•
Java has no preprocessor commands as in C++. Java is platform
independent and so its not needed
− Preprocessor example to check whether a variable is defined or
not, in C++
− #define Demo
− int main()
− { #ifdef Demo std::cout << "Demo Version";
−
else std::cout << "Non-Demo Version";
− #endif }
•
Java does not have #include but uses import.
•
Global variables are not present in Java. Constant is created using
final reserve word
OOP
62
Java and C++
•
•
Operators like &, *, or sizeof are not present in Java because the
pointer type is not included in Java
Multiple inheritance is not supported in Java
− Multiple inheritance is possible to an extent in Java using
interfaces
Java does not support user-defined operator overloading
•
•
•
•
•
•
•
•
•
•
#include <iostream>
using namespace std;
class Test { int x; public: Test() { x = 0; } Test(int i) { x = i;}
Test operator+(Test op2); void show(); };
// Overload addition.
Test Test::operator+(Test op2)
{ Test temp; temp.x = x + op2.x; return temp; }
void Test::show() { cout << x; }
int main() { Test a(1), b(2), c; c = a + b;
cout << "a + b = "; c.show(); cout << "\n"; return 0; }
•
OOP
63
Java and C++
•
•
Java: Object manipulation is done by reference
C++: Object manipulation is done by value (by default) but object
manipulation using reference can also be done
OOP
64
Java and C++
•
Java: Byte data type, which could contain values from -128 to 127, is
supported.
− byte b = 100; // works ok
− byte b = 200; // Compile error – loss of precision
OOP
65
Java and C++
•
•
•
•
•
•
•
Java: Object creation is done only using new operator
C++: Object creation can be done with or without new operator
Java: final modifier is used to prevent it from being modified
Java: abstract class cannot have objects, as new cannot be applied
Package scope in java is an alternate to friend in C++
Method overloading is allowed in Java
Java: Methods are dynamically bounded to definition by default
•
#include <iostream>
•
•
•
•
•
using std::cout;
class Test { public: int x;
// Constructor
Test(int xValue) { cout << "Test constructor called\n"; x = xValue; }
};
•
•
int main() { Test Testing(10);
cout << "Value Entered: " << Testing.x << "\n "; return 0; }
OOP
66
Event Handling in Java
•
•
•
•
Handling user input: Pressing a key or clicking the mouse or …
The actions generated by the events are communicated to the
programs using Abstract Windowing Toolkit (AWT)
Event handling is done using:
− Event Object: Event is represented using Objects in Java
− Event Source: object that generates the event. ActionEvent
object contains the information
− Event Handler: Method that processes the event. Event Object is
passed as parameter to this method
Event Classes
− EventObject class, which is the top of the event class hierarchy,
is present in the java.util package
− getSource() method present in the EventObject class returns that
object that caused the event
− The nature of the event like whether a mouse was pressed or
released or moved can be identified using getId() method
− AWT also handles semantic and low-level events
OOP
67
Event Handling in Java
•
•
Semantic Events:
− Higher-level events useful to manage activities of user interface
components
− ActionEvent object is generated whenever a component is
activated.
− AdjustmentEvent object is generated when adjustment elements
like scrollbar is used.
− TextEvent object is generated when the text is modified.
− ItemEvent object is generated when an item from a given list or
checkbox or choice is selected
Low-level events:
− Input or GUI activities that occur on the screen
− ContainerEvent object is generated whenever a component is
added or removed from the container.
− ComponentEvent object is generated when the component is
resized or moved or etc.
− FocusEvent object is generated when the component is made
focus for input.
− KeyEvent object is generated when any key in the keyboard is
pressed or released.
OOP
68
Event Handling in Java
•
•
69
Low-level events:
− WindowEvent object is generated during a window activity like
maximizing or minimizing or closing of a window.
− MouseEvent object is generated when the mouse is used.
− PaintEvent object is generated when the component is painted.
Event Listeners
− The occurrence of an event will cause an object to be generated
− This object is handled using the event listener
− Listeners can be removed from a component using
removeActionListener() method
− Semantic event listeners include ActionListener,
AdjustmentListener, ItemListener, TextListener, etc.
− Low-level event listeners include ComponentListener,
ContainerListener, FocusListener, KeyListener, MouseListener,
MouseMotionListener, WindowsListener, etc
OOP
Event Handling in Java
OOP
70
Event Handling in Java
•
•
•
Program starts with main method
EventTest object created at main method invokes the constructor of
EventTest class
In order to handle events, a listener object is created and then
registered with the button
OOP
71
Event Handling in Java
•
•
•
•
•
Upon user interaction with the button click, the ActionEvent object
is created and the actionPerformed method in the ActionListener
interface is executed. This changes the button's text
Generally, Java applications start from main method
Applets don't have a main method and are used to run over a browser
or using appletviewer
Applets start their execution from an init method
Generally, Applets are used for client side programming over the
Internet
OOP
72
Event Handling in Java
•
Applet example
OOP
73
Programming in Object Oriented Languages
•
•
•
C#: Sharp Develop software
C++: g++ compiler
Java: Java SDK
OOP
74
Download