Four main OOP concepts abstraction • creation of well-defined interface for an object, separate from its implementation e.g., Vector in Java e.g., key functionalities (init, add, delete, count, print) which can be called independently of knowing how an object is implemented encapsulation keeping implementation details “private”, i.e., inside the implementation hierarchy an object is defined in terms of other objects Composition => larger objects out of smaller ones Inheritance => properties of smaller objects are “inherited” by larger objects polymorphism use code “transparently” for all types of same class of object i.e., “morph” one object into another object within same hierarchy
188
Embed
Four main OOP concepts abstraction creation of well-defined interface for an object, separate from its implementation e.g., Vector in Java e.g., key functionalities.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Four main OOP concepts abstraction
• creation of well-defined interface for an object, separate from itsimplementation e.g., Vector in Java e.g., key functionalities (init, add, delete, count, print) which can becalled independently of knowing how an object is implemented encapsulation
keeping implementation details “private”, i.e., inside the implementation hierarchy an object is defined in terms of other objects Composition => larger objects out of smaller ones Inheritance => properties of smaller objects are “inherited” by largerobjects polymorphism
use code “transparently” for all types of same class of object i.e., “morph” one object into another object within same hierarchy
Advantages
• Can create new programs faster because we can reuse• code• Easier to create new data types• Easier memory management• Programs should be less bug-prone, as it uses a stricter• syntax and type checking.• `Data hiding', the usage of data by one program part• while other program parts cannot access the data• Will whiten your teeth
Disadvantages
• disadvantages of C++ over Java:• Java protects you from making mistakes that
C/C++ don’t, as you’ve• C++ has many concepts and possibilities so it
has a steep learning curve• extensive use of operator overloading, function
overloading and virtual• functions can very quickly make C++ programs
very complicated• shortcuts offered in C++ can often make it
completely unreadable, just like in C
Sample Hello.cpp
#include <iostream.h>
#include <stdio.h>
using namespace std;
main() {
cout << "hello world\n";
cout << "hello" << " world" << endl;
}
Data types
• simple native data types: bool, int, double, char, wchar_t
• bool is like boolean in Java• wchar_t is “wide char” for representing data from• character sets with more than 255 characters• modifiers: short, long, signed, unsigned, e.g.,
short int• floating point types: float, double, long double• enum and typedef just like C
Operators
• same as C, with some additions
• if you recognize it from C, then it’s pretty safe to
• assume it is doing the same thing in C++
• Operator overloading…
Type conversions
• All integer math is done using int datatypes, soall types (bool, char, short, enum) are promotedto int before any arithmetic operations areperformed on them• Mixed expressions of integer / floating typespromote the lower type to the higher typeaccording to the following hierarchy:int < unsigned < long < unsigned long< float < double < long double
Branching and Looping
• if, if/else just like C and Java
• while and for and do/while just like C and Java
• break and continue just like C and Java
• switch just like C and Java
• goto just like C (but don’t use it!!!)
Program structure
• just like in C• program is a collection of functions and
declarations• language is block-structured• declarations are made at the beginning of a
block;• allocated on entry to the block and freed when
exitingthe block• parameters are call-by-value unless otherwise
specified
Arrays
• similar to C• dynamic memory allocation handled using new and
delete instead of malloc (and family) and freeexamples:int a[5];char b[3] = { ’a’, ’b’, ’c’ };• double c[4][5];• int *p = new int(5); // space allocated and *p set to 5• int **q = new int[10]; // space allocated and q = &q[0]• int *r = new int; // space allocated but not initialized
Defining c++ functions• a function’s “signature” is its name plus number and type of arguments• you can have multiple functions with same name, as long as the signatures
are different example:• void foo( int a, char b );• void foo( int a, int b );• void foo( int a );• void foo( double f ); main() {foo( 1,’x’ );foo( 1,2 );foo( 3 );foo( 5.79 );} • OVERLOADING – when function name is used by more than one function
Pointers and References• pointers are like C:• int *p means “pointer to int”• p = &i means p gets the address of object i. references are not like C!! they
are• basically aliases – alternative names – for the values stored at the indicatedmemory locations, e.g.:int n;int &nn = n;double a[10];double &last = a[9];The difference between them:int a = 5; // declare and define aint *p = &a; // p points to aint &refa = a; // alias (reference) for a*p = 7; // *p points to a, so a is assigned 7
refa = *p + 1; // a is assigned value of *p=7 plus 1
UNIT-II
CLASSES AND OBJECTS
Classes and Objects
• Class:It is defined as blueprint or it is a collection of objects
• Objects:is an instance of a class
Declaring Class • Almost like struct, the default privacy specification is private
whereas• with struct, the default privacy specification is publicExample:class point {double x, y; // implicitly privatepublic:void print();void set( double u, double v );};• classes can be nested (like java)• static is like in Java, with some weird subtleties
Classes: function overloading andoverriding
overloading:• when you use the same name for functions with different
signatures• functions in derived class supercede any functions in
base class with the same name overriding:• when you change the behavior of base-class function in
a derived class• DON’T OVERRIDE BASE-CLASS FUNCTIONS!!• because compiler can invoke wrong version by mistake
Access specifiers
public public members can be accessed from any function private members can only be accessed by class’s own members and by
“friends” (see ahead)Protected Class members, derived, and friends. “access violations” when you don’t obey the rules... can be listed in any order can be repeated
Constructors and destructors
constructors are called ctors in C++ take the same name as the class in which they
are defined, like in Javadestructors are called dtors in C++ take the same name as the class in which they
are defined, preceded by a tilde (˜)• sort of like finalize in Java• ctors can be overloaded and can take
arguments• dtors can not• default constructor has no arguments
More coding…
class point{double x,y;public:point() { x=0;y=0; } // defaultpoint( double u ) {x =u; y=0; }// conversionpoint( double u, double v ){ x =u; y =v;}...}
Operator overloading
• Most operators can be overloaded in cpp
• Treated as functions
• But its important to understand how they really work
LIST OF OPERATORS
• +• ~• -• !• =• *• /=• +=• <<• >>
• &&• ++• []• ()• new• delete• new[]• ->• >>=
Operators which cant beoverloaded
• .• .*• ::• ?:
Types of overloading
• Unary overloading
• Binary overloading
Inheritance
• Objects are often defined in terms of hierarchical classes with a base class and one or more levels of classes that inherit from the classes that are above it in the hierarchy.
• For instance, graphics objects might be defined as
follows:
Inheritance (continued)
class A : base class access specifier B{
member access specifier(s):...
member data and member function(s);...
}
Valid access specifiers include public, private, and protected
Syntax for Inheritance
class derivedClass : public baseClass { private : // Declarations of additional members, if needed. public: // Declarations of additional members, if needed. protected: // Declarations of additional members, if needed.}
The derived class inherits from the base class: all public members,all protected members (see later), and the default constructor
The additional members defined can have the same name (and type) as
those of the base class (as when some base members are to be redefined)
Hierarchy
Example of Inherited Classes
class Shape { protected: int width, height; public: void setDims (int a, int b){
width=a; height=b;} };
class Rectangle: public Shape { public: int area ( ) {
return (width * height); }};
class Triangle: public Shape { public: int area ( ) { return (width * height/2); }};
class Square: public Rectangle { public: void setDims (int a){
width=a; height=a;}};
More on Inheritance Syntax
class derivedClass : protected baseClass { …};// Effect: all public members inherited from baseClass are // now protected members of derivedClass
class derivedClass : private baseClass { …};// Effect: all public and protected members inherited from // baseClass are now private members of derivedClass
Multiple inheritance A class can inherit several classes at once:class derivedClass:public baseClass1,public baseClass2{ …};Remark: Not recommended
Virtual Functions
class Object3D { virtual void intersect(Ray *r, Hit *h);};
class Sphere : public Object3D { virtual void intersect(Ray *r, Hit *h);};
myObject->intersect(ray, hit);
If a superclass has virtual functions, the correct subclass version will automatically be selected
Sphere *mySphere = new Sphere();Object3D *myObject = mySphere;
A superclass pointer can reference a subclass object
Actually calls Sphere::intersect
Sup
ercl
ass
Sub
clas
s
Pure Virtual Functions
class Object3D { virtual void intersect(Ray *r, Hit *h) = 0;};
A pure virtual function has a prototype, but no definition. Used when a default implementation does not make sense.
A class with a pure virtual function is called a pure virtual class and cannot be instantiated. (However, its subclasses can).
Basic Terminology:Polymorphism
• Polymorphism means “having many forms”. It allows different objects to respond to the same message in different ways, the response specific to the type of the object.
E.g. the message displayDetails() of the Person class should give different results when send to a Student object (e.g. the enrolment number).
UNIT-III
IO STREAMS
Input/Output
• Not part of the language; implemented in• library (like C and Pascal)• The C I/O library stdio.h is available• quite cryptic to use• fprint, fprintf, etc.• The C++ library iostream is better• type-safe• extensible• very easy to use
Iostream Basics
• << is "put to" operator
• >> is "get from" operator
Three standard streams: cout, cin, cerr
std::cin >> x;
std::cout << “Hello world!”;
std::cerr << “Oops!”;
std::cout << x;
C++ Input/Output Library
• The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream classes. The most basic stream classes are the standard input/output streams:
• istream cin built-in input stream variable; by default hooked to keyboard
• ostream cout built-in output stream variable; by default hooked to console
• header file: <iostream>• C++ also provides stream types for reading from and writing to files:• ifstream inFile; // input file stream object• ofstream outFile; // output file stream object• header file: <fstream>
Standard Stream Objects
• cin – istream class, “tied to” (connected to) the standard input device (keyboard)
• cout – ostream class, “tied to” standard output device
• cerr – ostream class, standard error output, unbuffered
• clog – ostream class, also to standard error, buffered
• Normally, cin or cout or file stream is used sequentially
• Using the stream member functions seekp( ) and write( ), we can do random file access
Ways of handling errors in C++
• Errors can be dealt with at place error occurs– easy to see if proper error checking implemented– harder to read application itself and see how code works
• Exception handling – makes clear, robust, fault-tolerant programs– C++ removes error handling code from "main line" of program
• Common failures– new not allocating memory– out of bounds array subscript– division by zero– invalid function parameters
Why exception handling?• Exception handling - catch errors before they occur
– deals with synchronous errors (i.e., divide by zero)– does not deal with asynchronous errors - disk I/O
completions, mouse clicks - use interrupt processing– used when system can recover from error
• exception handler - recovery procedure
– typically used when error dealt with in different place than where it occurred
– useful when program cannot recover but must shut down cleanly
• Exception handling should not be used for program control– not optimized, can harm program performance
Exception handling
• Exception handling improves fault-tolerance– easier to write error-processing code– specify what type of exceptions are to be caught
• Most programs support only single threads– techniques in this chapter apply for multithreaded OS as well
(Windows NT, OS/2, some UNIX)
• Exception handling another way to return control from a function or block of code
When Exception Handling Should Be Used
• Error handling should be used for– processing exceptional situations– processing exceptions for components that cannot handle them
directly– processing exceptions for widely used components (libraries,
classes, functions) that should not process their own exceptions– large projects that require uniform error processing
Other Error-Handling Techniques• Use assert
– if assertion false, the program terminates
• Ignore exceptions– use this "technique" on casual, personal programs - not
commercial!
• Abort the program – appropriate for nonfatal errors give appearance that program
functioned correctly
– inappropriate for mission-critical programs, can cause resource leaks
• Set some error indicator – program may not check indicator at all points the error could occur
Other Error-Handling Techniques con’t
• Test for the error condition– issue an error message and call exit– pass error code to environment
• setjump and longjump – in <csetjmp>– jump out of deeply nested function calls back to an error handler.
– dangerous - unwinds the stack without calling destructors for automatic objects (more later)
• specific errors – some have dedicated capabilities for handling them
– if new fails to allocate memory new_handler function executes to deal with problem
Exception Handling: try, throw, catch• A function can throw an exception object if it detects an error
– object typically a character string (error message) or class object
– if exception handler exists, exception caught and handled– otherwise, program terminates
• Format
– enclose code that may have an error in try block– follow with one or more catch blocks
• each catch block has an exception handler
– if exception occurs and matches parameter in catch block, code in catch block executed
– if no exception thrown, exception handlers skipped and control resumes after catch blocks
– throw point - place where exception occurred• control cannot return to throw point
1. Class definition
1.1 Function definition
1 // Fig. 13.1: fig13_01.cpp
2 // A simple exception handling example.
3 // Checking for a divide-by-zero exception.
4 #include <iostream>
5
6 using std::cout;
7 using std::cin;
8 using std::endl;
9
10 // Class DivideByZeroException to be used in exception
11 // handling for throwing an exception on a division by zero.
12 class DivideByZeroException {
13 public:
14 DivideByZeroException()
15 : message( "attempted to divide by zero" ) { }
16 const char *what() const { return message; }
17 private:
18 const char *message;
19 };
20
21 // Definition of function quotient. Demonstrates throwing
22 // an exception when a divide-by-zero exception is encountered.
23 double quotient( int numerator, int denominator )
52 cout << "\nEnter two integers (end-of-file to end): ";
53 }
54
55 cout << endl;
56 return 0; // terminate normally
57 }
try block encloses code that may throw an exception, along with code that should not execute if an exception occurs.
catch block follows try block, and contains exception-handling code.
UNIT-IV
AN OVERVIEW OF JAVA
History of a Young Java
• 1992 Oak for a PDA on a SPARC (*7)• 1995 Official release as Java – Internet• 1997 picoJava – Sun’s Java processor• 1998 RTSJ specification start as JSR-01• 1999 split into J2SE and J2EE• 2000 J2ME• 2002 RTSJ final release• 2002 first version of JOP ;-)
What is java?
• Developed by Sun Microsystems (James Gosling)
• A general-purpose object-oriented language
• Based on C/C++
• Designed for easy Web/Internet applications
• Widespread acceptance
Java Features (1)• Simple
– fixes some clumsy features of C++
– no pointers
– automatic garbage collection– rich pre-defined class library http://java.sun.com/j2se/1.4.2/docs/api/
• Object oriented– focus on the data (objects) and methods manipulating the
data
– all functions are associated with objects
– almost all datatypes are objects (files, strings, etc.)
• Interpreted– java compiler generate byte-codes, not native machine code
– the compiled byte-codes are platform-independent
– java bytecodes are translated on the fly to machine readable instructions in runtime (Java Virtual Machine)
• Portable– same application runs on all platforms
– the sizes of the primitive data types are always the same
– the libraries define portable interfaces
Java Features (2)
Java Features (3)
• Reliable– extensive compile-time and runtime error checking
– no pointers but real arrays. Memory corruptions or unauthorized memory accesses are impossible
– automatic garbage collection tracks objects usage over time
• Secure– usage in networked environments requires more security
– memory allocation model is a major defense
– access restrictions are forced (private, public)
Java Features (4)
• Multithreaded– multiple concurrent threads of executions can run
simultaneously
– utilizes a sophisticated set of synchronization primitives (based on monitors and condition variables paradigm) to achieve this
• Dynamic– java is designed to adapt to evolving environment
– libraries can freely add new methods and instance variables without any effect on their clients
– interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented
– can check the class type in runtime
Java Disadvantages
• Slower than compiled language such as C– an experiment in 1999 showed that Java was 3 or 4 times
slower than C or C++
title of the article: “Comparing Java vs. C/C++ Efficiency Issues to Interpersonal Issues” (Lutz Prechelt)
– adequate for all but the most time-intensive programs
Getting Started: (1)(1) Create the source file:
– open a text editor, type in the code which defines a class (HelloWorldApp) and then save it in a file (HelloWorldApp.java)
– file and class name are case sensitive and must be matched exactly (except the .java part)
Example Code: HelloWorldApp.java
/** * The HelloWorldApp class implements an application * that displays "Hello World!" to the standard output */ public class HelloWorldApp {
• Variables– dataType identifier [ = Expression]:– Example variable declarations and initializations:int x; x=5;
boolean b = true;Frame win = new Frame();String x = “how are you?”;
int[] intArray;intArray = new int[2];intArray[0] = 12;intArray[1] = 6;Person pArray = new Person[10];
Java system overview
Java Primitive Data Types
boolean either true or false
char 16-bit Unicode character (unsigned)
byte 8-bit integer (signed)
short 16-bit integer (signed)
int 32-bit integer (signed)
long 64-bit integer (signed)
float 32-bit floating-point (IEEE 754-1985)
double 64-bit floating-point (IEEE 754-1985)
JVM Data Types
reference Pointer to an object or array
int 32-bit integer (signed)
long 64-bit integer (signed)
float 32-bit floating-point (IEEE 754-1985)
double 64-bit floating-point (IEEE 754-1985)
• No boolean, char, byte, and short types– Stack contains only 32-bit and 64-bit data– Conversion instructions
Language basics (2)
• Flow of control– if, if-else, if-else if– switch– for, while, do-while– break– continue
Conditional Statements
The if – else statement
if ( boolean condition ) {
//statement sequence
} else {
//alternative statement sequence
}
Form of the if – else statement
Expression that evaluates to true or false
Block of statements that are executed if the condition is true
Statements executed otherwise
The else clause is optional, and may not be needed in every situation in which a segment of code is executed conditionally
Conditional Statements
Relational operators
The boolean condition in an if – else statement is often expressed as a test of a relationship between two variables.
Is x equal to y?
Is x greater than or equal to 0?
Is x less than size?
Is x not equal to 0?These tests are expressed in java in terms of the relational operators
== tests whether the expressions on the left and right are equivalent
<= Is expression on left less than or equal to exp. on right?
< Is expression on left less than expression on right?
> Is expression on left greater than expression on right?
>= Is expression on left greater than or equal to exp. on right?
!= tests whether the expressions on the left and right are not equal
(x == y)
(x >= 0)
(x < size)
(x != 0)
Conditional Statements
Relational operators
Be sure to distinguish between the relational operator == and the assignment operator =
x == y
x = y;
Tests if the contents of variable x are the same as the contents of variable y
Assigns the value stored in variable y to variable x (overwriting what is in x and leaving y unchanged)
Several of the relational operators use two characters for their symbol. There must NOT be a space between these two characters.
x == y x != y x <= y x >= y
Conditional StatementsExample
import java.util.Scanner; //needed for input stream classes
public class ConditionalStatementExample {
public static void main (String [ ] args) {
//convert a possibly negative integer received from the keyboard to
//its positive (absolute) value
System.out.println(“Enter an integer”);
Scanner console = new Scanner(System.in);
BufferedReader br = new BufferedReader(isr);
int theInteger = console.nextInt( );
if (theInteger < 0)
theInteger = - theInteger;
System.out.println(“The absolute value is: ” + theInteger);
}
}
If the integer is already positive, do nothing – else clause is not needed.
Conditional StatementsProgramming style
public static void main(String [ ] args) {
//list of statements indented 2 to 4 spaces
int num1, num2, num3 = 5;
num1 = 3 * num3 % 7;
num2 = 5 * num3 % 11;
//which number is larger
if (num1 >= num2) {
num1 += num3;
System.out.println(“The larger pair is num1, num3”);
}
else {
num2 += num3;
System.out.println(“The larger pair is num2, num3”);
}
}
Main block
Block of stmts. contained in if -- block
Block of stmts. contained in else -- block2 to 4 spaces
Conditional StatementsProgramming style
Note that if there is only a single statement in the if or else block, curly brackets are not needed. If there is more than one statement in one of these blocks, the curly brackets are required.
if (boolean condition)
statement;
else
statement;
if (boolean condition) {
statement;
statement;
}
else {
statement;
statement;
}Curly brackets optional
Curly brackets required
Conditional Statements
Nested if statements
Consider a function that assigns a letter grade to a numerical test score. (The test score is supplied as a parameter – writing functions will be explained fully later, right now we only wish to illustrate a nested if statement.
public char gradeGiver(int testScore) {
if (testScore >= 90)
return ‘A’;
else
if (testScore >= 80)
return ‘B’;
else
if (testScore >= 70)
return ‘C’;
else //testScore < 70
return ‘F’:
}
If the condition is satisfied, the program returns from this function call. Only scores less than 90 are evaluated further inside this function.
By convention, each if and else– block is indented 2 to 4 spaces.
Conditional Statements
Nested if statements
The preceding form is somewhat difficult to follow, therefore the preferred way of writing nested if statements is to use an else if construction.
public char gradeGiver (int testScore) {
if (testScore >= 90)
return ‘A’;
else if (testScore >= 80)
return ‘B’;
else if (testScore >= 70)
return ‘C’;
else
return ‘F’;
}
Introduction
• Java is a true OO language and therefore the underlying structure of all Java programs is classes.
• Anything we wish to represent in Java 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. They provide a convenient method for packaging a group of logically related data items and functions that work on them.
• A class essentially serves as a 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 a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism.
Classes
• A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
Circle
centreradius
circumference()area()
Classes
• A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
• The basic syntax for a class definition:
• Bare bone class – no fields, no methods
public class Circle { // my circle class}
class ClassName [extends SuperClassName]{
[fields declaration] [methods declaration]
}
Adding Fields: Class Circle with fields
• Add fields
• The fields (data) are also called the instance varaibles.
public class Circle { public double x, y; // centre coordinate public double r; // radius of the circle
}
Adding Methods
• A class with only data fields has no life. Objects created by such a class cannot respond to any messages.
• Methods are declared inside the body of the class but immediately after the declaration of data fields.
• The general form of a method declaration is:
type MethodName (parameter-list){
Method-body;}
Adding Methods to Class Circle
public class Circle {
public double x, y; // centre of the circle public double r; // radius of circle
//Methods to return circumference and area public double circumference() {
return 2*3.14*r; } public double area() {
return 3.14 * r * r; }}
Method Body
Data Abstraction
• Declare the Circle class, have created a new data type – Data Abstraction
• Can define variables (objects) of that type:
Circle aCircle;
Circle bCircle;
Class of Circle cont.
• aCircle, bCircle simply refers to a Circle object, not an object itself.
aCircle
Points to nothing (Null Reference)
bCircle
Points to nothing (Null Reference)
null null
Creating objects of a class
• Objects are created dynamically using the new keyword.
• aCircle and bCircle refer to Circle objects
bCircle = new Circle() ;aCircle = new Circle() ;
Creating objects of a class
aCircle = new Circle();bCircle = new Circle() ;
bCircle = aCircle;
P
aCircle
Q
bCircle
Before Assignment
P
aCircle
Q
bCircle
Before Assignment
Automatic garbage collection
• The object does not have a reference and cannot be used in future.
• The object becomes a candidate for automatic garbage collection.
• Java automatically collects garbage periodically and releases the memory used to be used in the future.
Accessing Object/Circle Data
• Similar to C syntax for accessing data defined in a structure.
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radiusaCircle.y = 2.0aCircle.r = 1.0
Using Circle Class// Circle.java: Contains both Circle class and its user class//Add Circle class code hereclass MyMain{ public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf); }}
• Inheritance allows a software developer to derive a new class from an existing one
• The existing class is called the parent class or superclass
• The derived class is called the child class or subclass.
• Creates an is-a relationship
The subclass is a more
specific version of the
Original• (Remember has-a is
aggregation.)
Book
NovelDictionary
Mystery History
Inheritance
• The child class inherits the methods and data defined for the parent class
• To tailor a derived class, the programmer can add new variables or methods, or can modify the inherited ones
• Software reuse is at the heart of inheritance
• By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software
95
Deriving Subclasses
• In Java, we use the reserved word extends to establish an inheritance relationship
class Dictionary extends Book {
// class contents}
Dictionary webster = new Dictionary();
webster.message();
webster.defMessage();
public class Book {
protected int pages = 1500;
public String message() { System.out.println(“Number of pages: ” + pages); }}
public class Dictionary extends Book {
private int definitions = 52500;
public void defMessage() { System.out.println(“Number of definitions” + definitions); System.out.println(“Definitions per page: ” + (definitions/pages)); }}
Number of pages: 1500
Number of definitions: 52500
Definitions per page: 35
Some Inheritance Details
• An instance of a child class does not rely on an instance of a parent class– Hence we could create a Dictionary object
without having to create a Book object first
• Inheritance is a one-way street– The Book class cannot use variables or
methods declared explicitly in the Dictionary class
98
The protected Modifier
• Visibility modifiers determine which class members are inherited and which are not
• Variables and methods declared with public visibility are inherited; those with private visibility are not
• But public variables violate the principle of encapsulation
• There is a third visibility modifier that helps in inheritance situations: protected
99
The protected Modifier
• The protected modifier allows a member of a base class to be inherited into a child
• Protected visibility provides
– more encapsulation than public visibility does
– the best possible encapsulation that permits inheritance
100
The super Reference
• Constructors are not inherited, even though they have public visibility
• Yet we often want to use the parent's constructor to set up the "parent's part" of the object
• The super reference can be used to refer to the parent class, and often is used to invoke the parent's constructor
The super Reference
• A child’s constructor is responsible for calling the parent’s constructor
• The first line of a child’s constructor should use the super reference to call the parent’s constructor
• The super reference can also be used to reference other variables and methods defined in the parent’s class
public class Book {
protected int pages;
Book(int numPages) { pages = numPages; }}
public class Dictionary {
private int definitions;
Dictionary(int numPages, int numDefinitions) { super(numPages); definitions = numDefinitions; }}
Multiple Inheritance
• Java supports single inheritance, meaning that a derived class can have only one parent class
• Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents
• Collisions, such as the same variable name in two parents, have to be resolved
• Java does not support multiple inheritance
• In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead.
104
Overriding Methods
• When a child class defines a method with the same name and signature as a method in the parent class, we say that the child’s version overrides the parent’s version in favor of its own.
– Signature: method’s name along with number, type, and order of its parameters
• The new method must have the same signature as the parent's method, but can have a different body
• The type of the object executing the method determines which version of the method is invoked
Overriding
• A parent method can be invoked explicitly using the super reference
• If a method is declared with the final modifier, it cannot be overridden
• The concept of overriding can be applied to data and is called shadowing variables
• Shadowing variables should be avoided because it tends to cause unnecessarily confusing code
public class Book {
protected int pages;
Book(int numPages) { pages = numPages; }
public void message() { System.out.println(“Number of pages: ” + pages); }}public class Dictionary {
protected int definitions;
Dictionary(int numPages, int numDefinitions) { super(numPages); definitions = numDefinitions; }
public void message() { System.out.println(“Number of definitions” + definitions); System.out.println(“Definitions per page: ” + (definitions/pages)); super.message(); }}
107
Overloading vs. Overriding
• data
• Overriding lets you define Don't confuse the concepts of overloading and overriding
• Overloading deals with multiple methods with the same name in the same class, but with different signatures
• Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature
• Overloading lets you define a similar operation in different ways for different a similar operation in different ways for different object types
108
Class Hierarchies
• A child class of one parent can be the parent of another child, forming a class hierarchy Book
NovelDictionary
Mystery Romance
109
Class Hierarchies• Two children of the same parent are called siblings
– However they are not related by inheritance because one is not used to derive another.
• Common features should be put as high in the hierarchy as is reasonable
• An inherited member is passed continually down the line
• Therefore, a child class inherits from all its ancestor classes
• There is no single class hierarchy that is appropriate for all situations
110
The Object Class
• A class called Object is defined in the java.lang package of the Java standard class library
• All classes are derived from the Object class
• If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class
• Therefore, the Object class is the ultimate root of all class hierarchies
The Object Class• The Object class contains a few useful methods, which
are inherited by all classes
• For example, the toString method is defined in the Object class
• Every time we have defined toString, we have actually been overriding an existing definition
• The toString method in the Object class is defined to return a string that contains the name of the object’s class together along with some other information
– All objects are guaranteed to have a toString method via inheritance, thus the println method can call toString for any object that is passed to it
The Object Class
• The equals method of the Object class returns true if two references are aliases
• We can override equals in any class to define equality in some more appropriate way
• The String class (as we've seen) defines the equals method to return true if two String objects contain the same characters
• Therefore the String class has overridden the equals method inherited from Object in favor of its own version
Packages
Package• A collection of related classes and/or interfaces• Examples: The Java API• java.lang Essential classes for the Java language• java.text Facilities for formatting text output• java.util Special utilities (e.g. Scanner)• java.net Network communication• Packages can be divided into subpackages• java.awt Classes for GUIs and graphics• java.awt.font Classes and interface for fonts• java.awt.geom Classes for 2-dimensional objects
User-Defined Packages
Packages enable a programmer organize the code into smaller logically related unitsA large program may consists of hundreds of classes (800 inone current project with NASA) Every class is part of some packageIf you do not specify a package a class becomes part of the defaultpackageAccess Classes defined within the same package can access one another
more easily (no need for imports, fully qualified names) Some classes, object fields only accessible to classes in
samepackage
Defining Packages
To define: add package statement to specify package containing the classes of a filepackage mypackage;…public class myClass { … } // myClass is part of mypackageMust be first non-comment statement in file_ Packages organized into subpackages using the notationfoo.subpackage:package mypackage.mysubpackage;…public class myClass2 { … } // myClass2 is part of// mysubpackage, which is// within mypackage_ Packages in Eclipse_ Select File®New®Package_ Enter the full name of the package
Class Access and Packagesclass access within a package Classes within a package can refer to each other without full
qualification If a class, or member within a class, is not declared public, it can only be accessed by other classes within the package Class access across packages A public class can be accessed from other packages Its name is fully qualified or it must be is imported to achieve this The public classes of a package can be seen as the interface of the package with the outside world Importing a package does not
automatically import subpackagesE.g. import java.awt.* does not import java.awt.font
• Error occurred in execution time • Abnormal termination of program • Wrong execution result
• Provide an exception handling mechanism in language system – Improve the reliability of application program – Allow simple program code for exeception check and
handling into source
Exception Definition
• Treat exception as an object • All exceptions are instances of a class extended from
Throwable class or its subclass.
• Generally, a programmer makes new exception class to extend the Exception class which is subclass of Throwable class.
Exception Definition
class UserErr extends Exception { } class UserClass { UserErr x = new UserErr(); // ... if (val < 1) throw x; }
class UserErr extends Exception { } class UserClass { UserErr x = new UserErr(); // ... if (val < 1) throw x; }
Exception Definition
• We can pass the object which contains a message for the exception in string form
class UserErr extends Exception { UserErr(String s) super(s); // constructor } class UserClass { // ... if (val < 1) throw new UserErr("user exception throw message"); }
class UserErr extends Exception { UserErr(String s) super(s); // constructor } class UserClass { // ... if (val < 1) throw new UserErr("user exception throw message"); }
Hierarchical Structure of Throwable Class
ObjectObject
ThrowableThrowable
ErrorError ExceptionException
RuntimeExceptionRuntimeException
...
......
Definition of Exception
• Error Class– Critical error which is not acceptable in normal
application program
• Exception Class– Possible exception in normal application
program execution – Possible to handle by programmer
System-Defined Exception
• Raised implicitly by system because of illegal execution of program
• When cannot continue program execution any more • Created by Java System automatically • Exception extended from Error class and
– When beyond the bound of index in the object which use index, such as array, string, and vector
• ArrayStoreException : – When assign object of incorrect type to element of array
• NegativeArraySizeException : – When using a negative size of array
• NullPointerException : – When refer to object as a null pointer
• SecurityException : – When violate security. Caused by security manager
• IllegalMonitorStateException : – When the thread which is not owner of monitor involves
wait or notify method
Programmer-Defined Exception
Exceptions raised by programmer
• Check by compiler whether the exception handler for exception occurred exists or not– If there is no handler, it is error
• Sub class of Exception class
Exception Occurrence
• Raised implicitly by system • Raised explicitly by programmer
– throw Statement
throw ThrowableObject; throw ThrowableObject;
Throwable class orits sub class
Throwable class orits sub class
Exception Occurrence
class ThrowStatement extends Exception { public static void exp(int ptr) { if (ptr == 0) throw new NullPointerException(); } public static void main(String[] args) { int i = 0; ThrowStatement.exp(i); } }
class ThrowStatement extends Exception { public static void exp(int ptr) { if (ptr == 0) throw new NullPointerException(); } public static void main(String[] args) { int i = 0; ThrowStatement.exp(i); } }
java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java:4) at ThrowStatement.main(ThrowStatement.java:8)
java.lang.NullPointerException at ThrowStatement.exp(ThrowStatement.java:4) at ThrowStatement.main(ThrowStatement.java:8)
Exception Occurrence
• throws Statement– When programmer-defined exception is raised, if
there is no exception handler, need to describe it in the declaration part of method
– When system-defined exception occurred, if programmer does not deal with it, it would be processed by default exception handler
– Simple function to output error message and exit
• Execution Order of Exception Handler
– Finally clause is executed independent of exception and catch
Exception Propagation
public class Propagate { void orange() { int m = 25, i = 0; i = m / i; } void apple() { orange(); } public static void main(String[] args) { Propagate p = new Propagate(); p.apple(); } }
public class Propagate { void orange() { int m = 25, i = 0; i = m / i; } void apple() { orange(); } public static void main(String[] args) { Propagate p = new Propagate(); p.apple(); } }
java.lang.ArithmeticException: / by zeroat Propagate.orange(Propagate.java:4)at Propagate.apple(Propagate.java:8)at Propagate.main(Propagate.java:11)
java.lang.ArithmeticException: / by zeroat Propagate.orange(Propagate.java:4)at Propagate.apple(Propagate.java:8)at Propagate.main(Propagate.java:11)
Exception Propagation
• Explicit Description for possibility of Exception Occurrence
– System-Defined Exception • Do not need to announce the possibility of exception
occurrence
– Programmer-Defined Exception • When it is not managed in correspond method, the
exception type should be informed. • Use the throws clause
Exception Propagation
class MyException extends Exception { } public class ClassA { // … public void methodA() throws MyException { // … if (someErrCondition()) throw new MyException(); // … } }
class MyException extends Exception { } public class ClassA { // … public void methodA() throws MyException { // … if (someErrCondition()) throw new MyException(); // … } }
What are Threads?
• A piece of code that run in concurrent with other threads.
• Each thread is a statically ordered sequence of instructions.
• Threads are being extensively used express concurrency on both single and multiprocessors machines.
• Programming a task having multiple threads of control – Multithreading or Multithreaded Programming.
A single threaded program
class ABC
{
….public void main(..)
{
…
..
}
}
begin
body
end
A Multithreaded Program
Main Thread
Thread A Thread B Thread C
start startstart
Threads may switch or exchange data/results
Java Threads
• Java has built in thread support for Multithreading
• Create a class that extends the Thread class• Create a class that implements the Runnable
interface
1st method: Extending Thread class
• Threads are implemented as objects that contains a method called run() class MyThread extends Thread {
public void run() { // thread body of execution } }• Create a thread: MyThread thr1 = new MyThread();• Start Execution of threads: thr1.start();
141
An exampleclass MyThread extends Thread { // the thread public void run() { System.out.println(" this thread is running ... "); }} // end class MyThread
class ThreadEx1 { // a program that utilizes the thread public static void main(String [] args ) {
MyThread t = new MyThread();// due to extending the Thread class (above)// I can call start(), and this will call// run(). start() is a method in class Thread.
t.start(); } // end main()} // end class ThreadEx1
2nd method: Threads by implementing Runnable interface
class MyThread implements Runnable{ ..... public void run() { // thread body of execution }}• Creating Object: MyThread myObject = new MyThread();• Creating Thread Object: Thread thr1 = new Thread( myObject );• Start Execution: thr1.start();
143
An exampleclass MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); }} // end class MyThread
class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); // due to implementing the Runnable interface // I can call start(), and this will call run(). t.start(); } // end main()} // end class ThreadEx2
144
Life Cycle of Thread
new
runnable non-runnable
dead
wait()sleep()suspend()blocked
notify()sleptresume()unblocked
start()
stop()
Three threads exampleclass A extends Thread{ public void run() { for(int i=1;i<=5;i++) { System.out.println("\t From ThreadA: i= "+i); }
System.out.println("Exit from A"); }
}
class B extends Thread{ public void run() {
for(int j=1;j<=5;j++) { System.out.println("\t From ThreadB: j= "+j); }
System.out.println("Exit from B"); }
}
class C extends Thread{ public void run() {
for(int k=1;k<=5;k++) { System.out.println("\t From ThreadC: k= "+k); }
System.out.println("Exit from C"); }
}
class ThreadTest{ public static void main(String args[])
{ new A().start(); new B().start(); new C().start();
} }
Run 1• [C:\jdk1.3\bin] threads [1:76] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5Exit from B
Run2• [C:\jdk1.3\bin] threads [1:77] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5Exit from BExit from A
Shared Resources
• If one thread tries to read the data and other thread tries to update the same date, it leads to inconsistent state.
• This can be prevented by synchronising access to data.
• In Java: “Synchronized” method: – syncronised void update()– {
• …
– }
150
the driver: 3rd Threads sharing the same object
class InternetBankingSystem { public static void main(String [] args ) { Account accountObject = new Account (); Thread t1 = new Thread(new MyThread(accountObject)); Thread t2 = new Thread(new YourThread(accountObject)); Thread t3 = new Thread(new HerThread(accountObject));
t1.start(); t2.start(); t3.start(); // DO some other operation } // end main()}
151
Program with 3 threads and shared object
class MyThread implements Runnable { Account account; public MyThread (Account s) { account = s;} public void run() { account.deposit(); }} // end class MyThread
class YourThread implements Runnable { Account account; public YourThread (Account s) { account = s; } public void run() { account.withdraw(); } } // end class YourThread
class HerThread implements Runnable { Account account; public HerThread (Account s) { account = s; } public void run() {account.enquire(); }} // end class HerThread
account
152
Monitor (shared object) exampleclass Account { // the 'monitor'// DATA Members int balance;
// if 'synchronized' is removed, the outcome is unpredictable public synchronized void deposit( ) { // METHOD BODY : balance += deposit_amount; }
• In Java, each thread is assigned priority, which affects the order in which it is scheduled for running. The threads so far had same default priority (ORM_PRIORITY) and they are served using FCFS policy.– Java allows users to change priority:
Thread Priority Exampleclass A extends Thread{ public void run() { System.out.println("Thread A started");
for(int i=1;i<=4;i++) { System.out.println("\t From ThreadA: i= "+i); }
System.out.println("Exit from A"); }
}
class B extends Thread{ public void run() { System.out.println("Thread B started");
for(int j=1;j<=4;j++) { System.out.println("\t From ThreadB: j= "+j); }
System.out.println("Exit from B"); }
}
Thread Priority Exampleclass C extends Thread{ public void run() { System.out.println("Thread C started");
for(int k=1;k<=4;k++) { System.out.println("\t From ThreadC: k= "+k); } System.out.println("Exit from C"); }}class ThreadPriority{ public static void main(String args[]) { A threadA=new A(); B threadB=new B(); C threadC=new C();
• Java provides a class definition for a type called String
• Since the String class is part of the java.lang package, no special imports are required to use it (like a header file in C).
• Just like regular datatypes (and like C), variables of type String are declared as:
String s1; String s2, s3; //etc.• Note that String is uppercase. This is the Java
convention for classnames.
Strings
• Initializing a String is painlesss1 = “This is some java String”;
• Note that double quotes are required.• Memory is allocated dynamically.• Think of above method as shortcut for more
standard way (assuming s1 has been declared):
s1 = new String(“This is some java String”);• new operator required to create memory for new
String object.
String methods
• Given a String object we can then access any public String method or instance variable (field).
• Best to think of analogy with C. Given a variable of some struct type, we can access any of the struct’s members. If one of these members is a pointer to a function, we can essentially call a function using the struct. (x.doit(x,…))
• In Java, this idea is taken quite a bit further, but the above analogy is a good start.
String Examples
• Best to see by way of example:String s = new String(“Hello”);
Char c = s.charAt(3);
System.out.println(c);
• Method charAt called on String object s taking single integer parameter.
• How might this look in a procedural language with structures? (homework)
Streams
• Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.)– it acts as a buffer between the data source and destination
• Input stream: a stream that provides input to a program– System.in is an input stream
• Output stream: a stream that accepts output from a program– System.out is an output stream
• A stream connects a program to an I/O object– System.out connects a program to the screen– System.in connects a program to the keyboard
Streams
• All modern I/O is stream-based• A stream is a connection to a source of data or to
a destination for data (sometimes both)• An input stream may be associated with the
keyboard• An input stream or an output stream may be
associated with a file • Different streams have different characteristics:
– A file has a definite length, and therefore an end– Keyboard input has no specific end
How to do I/O
import java.io.*;
• Open the stream
• Use the stream (read, write, or both)
• Close the stream
Why Java I/O is hard
• Java I/O is very powerful, with an overwhelming number of options
• Any given kind of I/O is not particularly difficult
• The trick is to find your way through the maze of possibilities
openuseclose
Opening a stream
• There is data external to your program that you want to get, or you want to put data somewhere outside your program
• When you open a stream, you are making a connection to that external place
• Once the connection is made, you forget about the external place and just use the stream
openuseclose
Example of opening a stream
• A FileReader is a used to connect to a file that will be used for input: FileReader fileReader =
new FileReader(fileName);
• The fileName specifies where the (external) file is to be found
• You never use fileName again; instead, you use fileReader
openuseclose
Using a stream
• Some streams can be used only for input, others only for output, still others for both
• Using a stream means doing input from it or output to it
• But it’s not usually that simple--you need to manipulate the data in some way as it comes in or goes out
openuseclose
Example of using a stream
int ch;ch = fileReader.read( );
• The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read
• The meaning of the integer depends on the file encoding (ASCII, Unicode, other)
openuseclose
Manipulating the input data
• Reading characters as integers isn’t usually what you want to do
• A BufferedReader will convert integers to characters; it can also read whole lines
• The constructor for BufferedReader takes a FileReader parameter: BufferedReader bufferedReader =
new BufferedReader(fileReader);
openuseclose
Reading lines
String s;s = bufferedReader.readLine( );
• A BufferedReader will return null if there is nothing more to read
openuseclose
Closing
• A stream is an expensive resource
• There is a limit on the number of streams that you can have open at one time
• You should not have more than one stream open on the same file
• You must close a stream before you can open it again
• Always close your streams!
openuseclose
Text files
• Text (.txt) files are the simplest kind of files– text files can be used by many different
programs
• Formatted text files (such as .doc files) also contain binary formatting information
• Only programs that “know the secret code” can make sense formatted text files
• Compilers, in general, work only with text
My LineReader class
class LineReader { BufferedReader bufferedReader;
LineReader(String fileName) {...}
String readLine( ) {...}
void close( ) {...}}
Basics of the LineReader constructor
• Create a FileReader for the named file: FileReader fileReader =
new FileReader(fileName);
• Use it as input to a BufferedReader: BufferedReader bufferedReader =
new BufferedReader(fileReader);
• Use the BufferedReader; but first, we need to catch possible Exceptions