INFS2609 Software Implementation
INFS2609 Software Implementation
INFS2609 Software Implementation
The Object Oriented Programming is an approach to the solution of problems in which all computations are performed in the context of objects. The objects are instances of programming constructs, normally called classes, which are data abstractions and which contain procedural abstractions that operate on objects
Advantages Modeling Simplicity enhances program design and productivity Modular and re-usable Classes are like blueprints for houses. Just as we can build many houses from the one blue print, we can also instantiate (create) many objects from the one class Objects can be reused within different programs Classes must have identity and allow for inheritance Encapsulation A class acts as a container to hold its features (variables and methods) and define which can be seen from outside and which are hidden Polymorphism Generalized constructions can be used to handle a wide range of existing and yet to be developed classes through extension Structure Programming: Programs modeled as a collection of small tasks Data and functions are not closely tied together and modules are difficult to reuses because complex references are difficult to disentangle Object is an instance of a class Basic Components Import Statement: Packages referred to class libraries Class declaration Java executes in particular order. All application must have one main class with a main method because it is always executed first. Methods: A sequence of instructions a class or an object follows to perform task
Public: Any instance (variable/method) with this qualifier is available to any program with access to the object (visible to the world) Private: Any instance (variable/method) with this qualifier is only available to methods of the class (visible to class) Protected: available to methods of any subclasses Static: refers to all instances within the class
INFS2609 Software Implementation Void: method will perform task but will not return any information on performing the task.
Always try to keep local class components private and class private - provides control and security over class components - because outside access to instance variable for the class possible only via methods
Data Types
Comments: Provides description to help programmers to understand the program // Single Line or /* */ Multiple Line
Integer: int (123) Long: very long numbers Double: real number (0.24) Char: single character Char letter = A; String: a string of characters Variable has 3 properties inherent within it a memory location to store value, the type of data store in the memory, the name used to refer to the memory Primitive data types are handles by value For variable the amount of memory space is fixed. Non primitive data types are handled by reference. Eg: objects and arrays Cannot declare the same variable more than once Eg: int x,y,z ; Fixed variable values so that it cannot be changed, final double GST_RATE=7.5 When we declare an object we must give it a name (identifier) Nomenclature using good name in programming Memory is requested during running not during compilation MyClass firstObject (Declare) firstClass = new MyClass (Create) Boolean expression an expression that is true / false. ! Not && AND || OR ^ Exclusive Or String concatenation: connecting two or more strings together to form a larger string String message = Just + 6*3 return Just 18 Size of a string cannot be determined by the type of data. Its only known once the value of variable is known/ when object is instantiated. Size of int/char is fixed and known from declaration Comparing String: String1.equals(String2) String methods: .charAt(2) , .indexOf(G), .length() etc \n new line \ escape character String conversion Int count = Integer.parseInt(input) / double p = Double.parseDouble(input)
Control Flow Statements 1. Decision Making Statement a. IF : executes an action only if the condition is true if (Boolean_Expression) {Statement_1;} else if (Boolean_Expression { Statement_2;} b. Switch : provides application with a structure for multiple selection i. A series of possible branches ii. Only one variable is being checked in each condition switch (variableName) case value1: /**instructions to be executed;**/ break; case value2: /**instructions to be executed;**/ break; /**more values can be addded**/ default: /**instructions for default case**/ 2. Loop/Repetition a. While loop : executes repeatedly as long as Boolean condition is true while (count <= number) { System.out.print(count + ", "); count++; } b. Do-While: executes the statement before checking if condition is true/false do { System.out.print(count + ", "); count++; } while (count <= number);
Summary of variable usages Class C {Declare class and instance variable here Public: value is publicly available outside the class Private value is not available outside the class Static: shared by all class instances (Class variable) Final: value does not change Method M { Declare all local variables here } Reading Input BufferedReader Keyb = new BufferedReader(new InputStreamReader(System.in)); String input = Keyb.readLine(); Manipulating Text Files Reading Text Files Step 1: Creating a file reader object FileReader r = new FileReader(input.txt); Step 2: Creating an input stream object Bufferedreader bR = new BufferedReader(r); Step 3: Invoking reading operation on input stream object String line = read.Line(bR); Writing Text Files Step 1: Creating a print writer object PrintWriter out = new PrintWriter(out.txt); Step 2: Writing to the file out.println(23.98); out.print(the value of x is+x); Step 3: Close file Out.close
Arrays A collection of values of the same type, all values in the list are referenced by the same name Why? Any time you need to keep a series of item for processing Each individual variable of an array is stored at a specific numbered position within the array and correspond with a number position in the array. Starts with 0 int testScores [] = new int [5]; int testScores [] = {70,50,80,85,90}; OR String [] grades = {HD,DN.CR,PS,FL}; OR int myArray[]; myArray = new int {1,2,3,4,5,6,7}; OR (array manipulation) String [] cities = new String [30]; Cities[27] = Sydney OR (multiple dimension) int [] [] myTwoDim = { {0,2,5,6} ,{0,4,6,4},{1,5,9,0}};
Array Lists Similar to array but can grow or shrink when needed AKA generic class because it takes other classes as parameter Cannot take primitive type (eg: double) as a parameter
Adding items: accounts.add(acc1); Accessing items: BankAccount bA = accounts.get(2); Inserting values: accounts.set(2,bA);
Graphic User Interface: pictorial interface to a program Built from GUI components Is event driven programming (an event occurs when the user interact with a GUI object) Swing set extends AWT (abstract windows toolkit) GUI Components Heavyweight: associated with native GUI components Eg: JApplet, JDialog, JFram, JWindow Lightweight: implemented by Java JPanel : holds user interface component JButton: triggers an event when clicked JCheckBox: two state component, either selected or not selected JLabel: non editable texts JList: list of item is displayed and a selection can be made JTextField: inputs data from keyboard/ display information Layout set rules on how to put various components Flow layout: default layout manager for a panel (place components from left to right) Border layout: default layout for JFrame content pane Grid layout: set components in rows and column Set bound: place components with absolute positioning Gridbag layout: detailed positioning with specifies grid size GUI Components Characteristic Content [ okButton = new JButton(OK);] Appearance [outputField = new JTextField(15);] Behavior [public void actionPerformed(ActionEvent evt) .. ]
Event driven Programming: use events and event handlers Event is an object that represents an action. When an object generates an event, it is called firing the event Methods that handle events are event handlers. Has three parts - Event Source (the GUI object with which user interacts) - Event Object (encapsulates information about the event that occurred) - Event Listener (receives an event object when it is notified by the event source that an event has occurred) class c_name extends JFrame implements ActionListener Public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == okButton)
Mutator Methods: Assign value, setxxx eg. outField.setText(grade); Accessor Methods: READ method, getxxx eg inputField.getText(); Operator instanceOf: test whether a particular object is an instance of a class or subclass of that class This keyword is used to refer to the calling object in the current class. Creating good interfaces Keep it simple Dont use too many colors and fonts on screen Navigation simple navigation route Who is the program for? Plain simple and easily understood Class Design State project requirements in clear concise descriptive language Express solution in pseudo code Plan the project using class diagram form OOD model using UML
Applets Small java applications that can be embedded and run in another application Included inside HTML documents to provide interactive executable content on a web page Security: can only communicate with originating host, cannot read or write to local computers file system. Creating: include <applet> </applet> tag in HTML file Import java.applet. Public class hello extends applet Control Applet life cycle: public void init() : initializes the applet void start() : start executing void stop() : stop executing void destroy(): clear applet out of memory void paint(): redraw applet Advantages: runs locally Provide consistent and rapid response to user Work at the speed of browser unlike CGI script works at the speed of server When to use? When program is required for networked use / communication
JDBC Java Database Connectivity Javas API for working with SQL Advantages - Easy to use and provide advance capabilities - Portable and secure on all java platforms Java API - Establish a connection with data source, send queries, update statement to data source, and process the results JDBC Database Drivers: understands how to convert SQL request for a database 1. JDBC-ODBC drivers Bridge to ODBC (provides connectivity to all databases on almost all platforms) Small scale applications 2. Native API partly Java drivers Converts JDBC into calls on native APIs like Oracle, IBM etc However, requires client machine to have vendor db libaries Intranet Applications 3. JDBC Net pure Java drivers Converts JDBC calls into DBMS independent net protocol Internet related applications 4. Native protocol pure Java drivers Converts JDBC protocols directly into a DBMS network protocol Work group level Prepared Statements - If you want to execute a statement object many times, it will normally reduce execution time to use a preparedstatement object instead - Contains an SQL statement that has been precompiled (when preparedstatement is executed, the DBMS can run the statement without having to compile it) - PreparedStatement updateEMP = con.prepareStatement(Update emp + set salary=? Where name =?);
Execute a query using statement object cmdPatients.executeUpdate(sql); **executeUpdate do not return data from data store
Return data from ResultSet object ResultSet rsPatients = cmdPatients.executeQuery(Select * from patient;); Eg: rsPatients.getString(firstname); Eg: rsPatients.next (retrieving values with loop)
Software Quality Usability : easier for users to work with the system Efficiency : machine efficiencies Maintainability: ease with which you can change the system Reliability: able to do what it supposed to do Reusability: high reusability can reduce costs and time in development
Encapsulation refers to combination of properties and methods in a single unit allows an object to maintain integrity of data by hiding it from other object
Java Packages A class in package is accessible to other classes outside of the package only if the class is declared public Testing Validates the implementation of the class Verifies your design and implementation Purpose: To uncover errors and failure in the implementation Aspects: Determine test activities and select test data Conduct test, compare test results to expected results Test plans: Black box testing (ignores internal structure, concentrates on external use) White box testing Integration testing Reliability testing (compile time error, run time errors) Test drivers Classes developed specifically to test the internal structure of the implementation Unit testing JUnit unit testing framework for java (used for repeated testing of a software system to ensure that any bugs have been fixed, no previously working methods have been broken as a result of changes and newly added features have not created with the existing software) Import junit.framework.TestCase; Advantages of JUnit
10
Using Interfaces Interface types are useful when write different versions of this class write one version that operates on an interface types write different implementations of the interface Limitations on using interfaces for callback: cannot make some classes implement your interface.
Inner/Nested Classes Class defined within the scope of another class Used to support the work of the classes in which they nested To organize the code Eg: WindowAdapter Advantages: can access the implementation of the object that created it including data that would otherwise be private directly reference variables and methods within the scope of the entire class reduce redundancies Static Instances variable / method is accessed throught a particular objects instantiation Static helps to determine whether a method/variable is a class or instance method 3 kinds of variable -Class (declared static) -Local (declared inside a method) -Instances (declared inside a class but not inside a method) Main method of java program is static so that main can be executed without instantiating an object that contains main. Static method do no operate in context of a particular object they cannot reference instance variable.Therefore public static void main (String [] args) { Average find = new Average(); System.out.print(find.findAverage(12,1,3)); } double fineAverage(double a, double b, double c) { }
11
Inheritance Is-a relationship New classes are created from existing classes by absorbing/reusing/inherit all the non private attributes and behavior of those classes Ancestor class /Superclass /Base class Descendent class / Subclass / Derived class Public class PartTimeEmployee extends Employee Constructor are not inherited, therefore to initialized it use super Public PartTimeEmployee(String number, String name) { super (number , name) } Java RMI: Remote Method Invocation Allows java object to invoke a method on another java object located on another computer Concept of distributed objects Invoke remote methods Works independently of platform or network used
12