Download presentation
Presentation is loading. Please wait.
1
Object Oriented Programming Using Java Language
Hala Dernayka
2
Basic Information SW: is a collection of independent applications tied together with bridging software (when needed). Building a SW needs 3 parties: Customer: The company or institute that needs the SW, Developer: Programming team, Users: people who will use the system. Distributed system: in which the separate parts of the system execute on different computers and communicate with one another to achieve their purpose. Distributes systems could be called Concurrent Systems, where number of programs (parts) are executing simultaneously on different machines and exchanging data between each other. deadlock: when two or more processes are making use of the same resource which is required by the other, (for example using the same printer or data), neither can be proceed. security must be guaranteed within distributed systems. The network design, the kinds of data permitted to be transmitted, and encryption techniques all play a part in ensuring security.
3
Software development phases
Analysis: getting the Requirements Specification: process of finding out what the SW should do and the environment in which it work. • Elicitation of requirements: Finding out what is required. • Specification of requirements: The production of the requirements specification document. Design: deciding how to achieve the requirements technically. Implementation: coding process Testing: includes: Verification: check if the programming is correctly coded, Validation: Checking with the customers that the SW does what customers required. Integration: putting the parts together with each other and existing components Maintenance : fixing, improving, adapting
4
Basic Vocabulary Abstraction Model
Selective examination of certain aspects of a problem The goal is to isolate those aspects that are important for some purpose and suppress those that are unimportant Many different abstractions of the same thing are possible, depending on the purposes for which they are made relative to the perspective of the viewer Model An abstraction used to understand or reason about some real object Omits nonessential details for its purposes
5
Abstract data Type (ADT)
An abstract data type specification describes a family of data structures not by an implementation, but by a list of services available on instances of a type, and the formal semantics of those services. An ADT is a behavioral specification for objects A class is an implementation of an ADT An object is an instance of a class
6
Objects & Classes Objects: are defined by Classes
States (attributes, data fields) characterized by variables (named) Services (behaviors, responsibilities) characterized by methods (operations) The services of an object represent its contractual commitment Classes used to create objects Define the common structure and services of their instances (objects of the class) Can provide additional services and states that are not associated with objects, but rather with the family of objects defined by the class (ex by using static).
7
OO Concepts Everything is an object.
Computation is performed by inter-objects communicating. Each object has its own memory. Every object is an instance of a class. A class simply represents a grouping of similar objects.
8
Format of a class class name public class Rectangle class header
data type data name data modifier { } Class modifier private int length; private int width; Returned value type Or void method name method header public int area() class body { return (length*width); } method modifier method body public Rectangle(int l, int w) {length=l; width=w;} Constructor: has class name Needed arguments ArgumentType ArgumentName
9
Constructors a constructor is a special method that is used to create and initialize a new object. When writing a constructor, remember that: it has the same name as the class it does not return a value it has no return type, not even void it typically sets the initial values of instance variables Constructors are commonly overloaded If no constructor is supplied you get a no argument one for free
10
Data Types There are eight primitive data types in Java:
integers: byte, short, int, long floating point numbers: float, double characters: char boolean values: boolean A variable can be an object. So it’s type can be a predefined class name like String, or a user defined class name Rectangle
11
Arrays (table) The values held in an array are called array elements
An array stores multiple values of the same type (the element type) The element type can be a primitive type or an object reference Therefore, we can create an array of integers, or an array of characters, or an array of String objects, etc. Example declarring array: int[] scores = new int[10]; Vectors are arrays of variable length that can hold objects only.
12
Type Conversion A type denotes the set of all legal values of that type Type Compatibility Type T1 is compatible with type T2 if a value of type T1 can appear whenever a value of type T2 is expected and vice versa Type conversion comes in two forms widening converts a type of a smaller to a type of a larger range e.g., int to long or short to double narrowing converts a type of a larger to a type of a smaller range e.g., float to int or double to float If B is a subclass of A, then we can replace any instance of A with an instance of B in any situation with no observable effect. If A responds to message m, then B responds to m. · All Numbers respond to + aNumber · All Collections respond to do: aBlock All Views respond to containsPoint: aPoint
13
Allowable Conversion Widening is carried out implicitly – you need say nothing float f = 10; Narrowing requires explicit casts. int j = (int) 37.7;
14
Wrappers Primitives can be wrapped in an object so they can participate as first class citizens of the object world This is necessary for instance if an int is to be placed in a Vector (an expandable array of objects) Wrappers offer lots of other class services Integer.parseInt(String) Float.isNan(float) Double.isInfinite(double)
15
Encapsulation We can take one of two views of an object:
internal - the variables the object holds and the methods that make the object useful external - the services that an object provides and how the object interacts From the external view, an object is an encapsulated entity, providing a set of specific services These services define the interface to the object an object is an abstraction, hiding details from the rest of the system Its inner workings are hidden to the client, which invokes only the interface methods
16
Encapsulation An object should be self-governing
Any changes to the object's state (its variables) should be made only by that object's methods We should make it difficult, if not impossible, to access an object’s variables other than via its methods The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished Methods Client Data
17
Access (Visibility) Modifiers
we accomplish encapsulation through the appropriate use of Access Modifiers Java has three visibility modifiers: public, protected, and private variables or fields that provide the object’s state should be declared with private or protected modifiers. Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients public methods are also called service methods Members declared without a visibility modifier have default visibility : public and can be accessed by any class in the same package
18
Access Modifiers Public Protected Package Private Class itself Yes
Package classes No Subclasses Unrelated
19
Visibility Modifiers public private Violate encapsulation Enforce
Variables Provide services to clients Methods
20
Other Attributes static – associated with class, shared by all instances. A static method can access only static fields. final – a final method cannot be overridden by children a final variable is a constant (it must be initialized) a final parameter to method is immutable abstract – declared but not fully defined; cannot instantiate an abstract class
21
Creating Objects Rectangle r = new Rectangle(10, 12);
Creating an object is called instantiation. An object is an instance of a particular class A class name can be used as a type to declare an object reference variable ex: String title; Rectangle r; No object is created with this declaration. An object reference variable holds the address of an object. The object itself must be created separately with the new operator to create an object Rectangle r = new Rectangle(10, 12); This calls the Rectangle constructor, which is a special method that sets up the object Because strings are so common, we don't have to use the new operator to create a String object. title = "Java Software Solutions" Once an object has been instantiated, we can use the dot operator to invoke its methods: System.out.print(title.length()); System.out.print(r.area());
22
Overloading The signature of a method or constructor is the sequence made up of the types of its parameters. Return type, parameter names and the final attribute are not part of a signature. Overloading is the ability of different methods or constructors to share the same name. Rule: If two methods or constructor in a class have different signature, then they may be overloaded. Overloading should not hinder readability. Thus, if two methods share the same name, they should differ either by number of arguments or their types or both.
23
Inheritance Inheritance, the ability of a class to inherit capabilities and features form a parent class. Inheritance defines an is-a relationship. This is different from aggregation which forms a has-a relationship. An inheriting class is called a subclass. Its parent is its superclass.
24
Class Inheritance in Java
Java uses the term extends when one class is a subclass of another. This reflects the principle that a class has an is-a relationship with its superclasses. Subclasses can access all public and protected members of their ancestors. A subclass can override any non-final visible method of its superclass, but may not alter the return type.
25
Construction of Objects
The fields of the superclass are initialized. One of the constructors of the superclass is invoked. The fields of the subclass are initialized. One of the constructors of the new class is invoked.
26
Subtypes Each class defines a type All instances of the class constitute the values of this type. As every instance of a subclass is also an instance of its superclass, the type defined by the subclass is a subtype of that defined by its superclass
27
Principle of Substitutability
Java follows the “Principle of Substitutability” If B is a subtype of A, then we can replace any instance of A with an instance of B in any situation with no observable effect Substitutability & Subtypes The term subtype implies substitutability E.g., in Java, we may insist on parameters of a certain type – subtypes may be used here. We may also create arrays of a certain type – again, subtypes work here. All subclasses are assumed to be subtypes
28
Example class A { void print() {
System.out.println("This is class a"); } class B extends A { int bnum; void print(){ System.out.println("This is class b"); public class Test { public static void main(String [] args) { A a1 = new A(); B b1 = new B(); B b2; a1.print(); b1.print(); b1.bnum = 5; b2 = a1; b2.print(); System.out.println("Bnum " + b2.bnum); b2=b1; }}
29
Overriding vs Overloading
In Java you may override a method, but you can never overload it from a subclass. Overriding is supported by polymorphic method invocation, where the method selected is the one provided by the class closest to the one of the object receiving the message. An overriding method m can invoke the method it overrides by sending itself the message super.m() Super is also useful in constructors to select an appropriate constructor from the parent class. It must appear as the first statement in the child’s constructor.
30
Polymorphism in Java A method’s signature is made up of
name parameters (number, order and type) return type not considered for overloading purposes in Java Two common usages Same class and name, different parameters List() {…} List(int size) {…} Override a parent’s method Must have the same signature public class Object {…} public String toString() { return } public class Employee extends Object {…} public String toString() { return name; }
31
Replacement vs Refinement
Replacement – overriding a method in parent class Refinement – adding a prologue and/or epilogue to parent method.
32
The Equality Issue In Java, the == operator means is the same object. This is often called the identity operator In the case of primitives this gives you what you expect, but not so for objects. To compare the values of two objects you use the equals(obj) service
33
Java’s Compromise Java does not support true multiple inheritance
does support the “interface” construct You get the method signatures from the interface, but you must implement all of the methods interface dummy { void method1(); } class realOne implements dummy { void method1() { //something cool
34
Interfaces An interface is like a very abstract class
It can only specify a contract – no method implementations are allowed Interfaces can also declare and define static constants, but not instance variables Interfaces cannot specify any static methods, and their instance methods must all be public
35
Interfaces The interface and class have an implementation relation, but the interface is not married to to just one class. Interfaces contain no implementation and no parts. it’s a contract to which many classes may agree. If a class or interface C extends another class or interface T, then C is a subtype of T. If class C implement interface T, C is a subtype of T.
36
Delegation versus Inheritance
Delegation is the act of an object delegating responsibility for the handling of a service to some other object. To some degree, aggregation can be used for delegation, in that I could have a copy of the objects to whom I pass responsibility as one of my parts. Often though, delegation allows the delegates to declare their interest, and the delegator has no a priori idea of who will be interested in these messages.
37
Delegation to Listeners
This is an inversion of simple delegation, in which the delegatees register their interest in an event. The delegator is just responsible to notify them of the event (message, exception, whatever). In Java those willing to be delegated a service are called listeners. They listen for some event, and then perform some appropriate action. The new event model in Java is based totally on delegation of events to interested listeners.
38
Abstract MouseAdapter
public abstract class MouseAdapter implements MouseListener { // this implements all services, but is declared abstract // it exists for its heirs; can have no clients // Invoked when the mouse has been clicked on a component. public void mouseClicked(MouseEvent e) { } // Invoked when a mouse button has been pressed on a component. public void mousePressed(MouseEvent e) { } // Invoked when a mouse button has been released on a component. public void mouseReleased(MouseEvent e) { } // Invoked when the mouse enters a component. public void mouseEntered(MouseEvent e) { } // Invoked when the mouse exits a component. public void mouseExited(MouseEvent e) { } }
39
Adapters – Dedicated Listeners
Adapters are specialized objects dedicated to listening for just one event type from one source. JLabel pressMe = new JLabel(); pressMe.setText(“Press Me"); pressMe.addMouseListener(new java.awt.event.MouseAdapter(){ public void mousePressed(MouseEvent e) { pressMe_mousePressed(e); } } ); This is an example of an anonymous class that is subclassed off an abstract class MouseAdapter.
40
Applet’s Methods The class Applet provides lots of services.
All instances of Applet respond to the messages init() -- called when browser first encounters applet start() -- called when browser visits page containing applet stop() -- called when browser leaves page destroy() -- called when browser decides applet is irrelevant paint(g) -- called when applet’s view is being uncovered, or originally shown The default versions of these functions (provided by Applet) do nothing.
41
Putting Applet Together
import java.applet.Applet; import java.awt.Graphics; public class firstApplet extends Applet { StringBuffer message; void concat(String actiontodo) { message.append(actiontodo); repaint(); } public void init() { message = new StringBuffer(); concat("init "); public void start() { concat("start "); } public void stop() { concat("stop "); } public void destroy() { concat("destroy "); } public void paint(Graphics g) { g.drawString(message.toString(), 10, 20); }
42
HTML Parameters The web page invokes the applet and tells it where and how big of space it has to run Simplest version of an invocation <APPLET CODE=‘firstApplet.class’ WIDTH=90 HEIGHT=120> </APPLET> The class file needs to be in HTML source directory . You can also pass parameters, specify the location of the code base, load an archive.. Parameters are passed as name / value pairs <PARAM NAME=“SoundFile” VALUE=“bluemoon.au”>
43
Swing Components JWindow, JFrame and JDialog
JDialog is commonly used for simple dialogs, e.g., warnings and information. JFrame and JWindow are like Frame and Window, but tailored to hold lightweight components.
44
Layout Managers Layout managers are: BorderLayout BoxLayout CardLayout
FlowLayout GridLayout GridBagLayout
45
Border Layout Example import java.awt.*; import javax.swing.*;
public class Border extends JApplet { public Border () { getContentPane().setLayout(new BorderLayout()); getContentPane().add("South", new JButton("South")); getContentPane().add("North", new JButton("North")); getContentPane().add("East", new JButton("East")); getContentPane().add("West", new JButton("West")); getContentPane().add("Center", new JButton("Center")); }
46
Examples Swing Label Button RadioButtons CheckBox ComboBox SplitPane
LayeredPanel TextField Password List InternalFrame
47
The MVC Paradigm The core of an application or any part of an application is a model which maintains the state of the world (or piece of the worlds). A view is a user perception of the state of a model. Often, we want multiple views of the same model. A controller is how a user interacts with the model, typically through some view. Even a button has a model, its state; a view, its appearance; and controller to sense mouse activity in the button’s region. A table has a model which contains its state, and hence provides contents to the table’s cells.
48
Java I/O Java supports two types of IO: Stream IO Random access IO
A stream is a sequence of bytes. Stream-based IO supports reading or writing data sequentially. A stream may be opened for reading or writing, but not reading and writing. There are tow types of streams: the byte streams and the character stream. Random access IO Random access IO support reading and writing data at any positions of a file. A random access file may be opened for reading and writing.
49
Byte Streams
50
Character Streams
51
Using Reader and Writer
BufferedReader file_in = new BufferedReader( new FileReader("foo.in")); BufferedReader in new InputStreamReader(System.in)); PrintWriter file_out = new PrintWriter( new BufferedWriter( new FileWriter("foo.out"))); Writer out = new BufferedWriter( new OutputStreamWriter(System.out));
52
Reading Keyboard Input
The System.in object is used to create an InputStreamReader object The InputStreamReader object is used to create a BufferedReader object This creates an input stream that treats input as characters and buffers them so that input can be read a line at a time The readLine method of the BufferedReader class reads an entire line of input as a String
53
Example import java.io.* // needed to get access to I/O //Output
System.out.print(aString); System.out.println(aString); //Input (one value per line / later we’ll do better) BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); int anInt1 = Integer.parseInt(stdin.readLine()); // one way int anInt2 = Integer.valueOf(stdin.readLine()).intValue(); //2nd way double aDouble = Double.valueOf(stdin.readLine()).doubleValue(); Integer is a class, each of whose instances holds a single int Double is a class, each of whose instances holds a single double
54
Applications versus Applets
Java applications run like any other program, with all the rights and privileges thereto appertaining Applets run in a sandbox, Internet browser or applet viewer The sand box provides services, but limits what applet can do No reading or writing files on local machine (just from host) No network connections, except back to host No inter-applet communication except to others from same host
55
Hello Java Application
class Hello { /** A Java app prints "Hello!" */ public static void main (String args[]) { System.out.println("Hello!"); /* System.out refers to the standard output */ }
56
Vocabulary public static void main String args[] System System.out
accessible by clients of class static belongs to the class; non-static belong to instances void returns nothing main must be public; called by you execute application String args[] array of Strings from command line (does not include class name) System base class containing system items like console handles System.out console output stream
57
Hello Java Applet import java.awt.*; import java.applet.Applet;
public class HelloApplet extends Applet { public void paint(Graphics g) { Dimension d = getSize(); g.setColor(Color.black); g.fillRect(0,0,d.width,d.height); g.setFont(new Font("Helvetica", Font.BOLD, 24)); g.setColor(new Color(255, 215, 0)); // gold color g.drawString("Welcome!", 40, 25); g.drawImage(getImage(getCodeBase(), "swing.gif"), 20, 60, this); }
58
Vocabulary java.applet.Applet extends Applet paint Graphics getSize( )
Applet class defined in the directory <classpath>/java/applet/ extends adds or overrides services from a parent class (super type) Applet the class defining standard applet services and parts paint called when Component image is originally drawn or must be repaired (uses clipping) Graphics the class associated with graphical contexts getSize( ) returns dimension of Applet getImage(getCodeBase(), "swing.gif") Applets can acquire images; code base is directory of Applet
59
Hello Java Applet HTML <title>Test</title> <hr>
<applet code=“HelloApplet.class" width=300 height=150> </applet>
60
Hello Java JApplet import javax.swing.*; import java.awt.*;
public class HelloJApplet extends JApplet { public void init() { Container contentPane = getContentPane(); Icon icon = new ImageIcon("swing.gif", “Swinging Duke"); JLabel label = new JLabel("Welcome!", icon, SwingConstants.CENTER); contentPane.add(label, BorderLayout.CENTER); }
61
Vocabulary JApplet SwingConstants BorderLayout
the class defining standard applet services and parts in the swing framework getContentPane called to get the Container into which “lightweight” Swing components are placed ImageIcon class each of whose instances holds a named small image SwingConstants interface holding standard Swing constants BorderLayout interface holding standard BorderLayout constants
62
Threads Thread A thread is not a program
A thread is a sequentially executed stream of commands Usually a lightweight process A thread is not a program Runs within the resources allocated to a program It does have its own execution context (stack, program counter, register) Multiple threads of a program share resources and can refer to common objects Every program has at least one thread
63
Thread Life Cycle Running Blocked Create Finished Ready Yield Start
Service Terminate Create – new thread is allocated Running – thread is executing Ready – thread is waiting for the processor Blocked – thread is waiting on a requested service Finished – thread has been stopped and deallocated
64
Java Threads Like everything else, a thread is an instance of a class.
Part of the java.lang package Provides basic behaviors Starting Stopping Sleeping Yielding Priority management A simple form of monitors The run method, by default is empty There are two ways Subclass Thread and override run Implement the Runnable interface
65
Sample Java Thread class SimpleThread extends Thread {
public SimpleThread(String str) { super(str); //sets thread’s name } public void run() { for (int i = 0; i < 10; i++) { System.out.println(i + " " +getName()); try { sleep((int)(Math.random() * 1000)); // one second delay } catch (InterruptedException e) { } System.out.println("DONE! " + getName()); public class Test { public static void main (String[] args) { new SimpleThread("Jamaica").start(); new SimpleThread("Fiji").start();
66
Creating & Starting a Thread
Creating a thread instances the class No resources have been allocated to it yet From here, the only thing you can do is call the start method myThread = new Thread(this,”My Thread”); Used as part of the Runnable interface “this” sets the context for the thread “My Thread” sets the name myThread = new MyThreadClass(”My Thread”); Used when inheriting Context is set to the current object Starting a thread myThread.start(); Allocates the resource Starts the thread running Returns control to existing thread
67
Thread or Runnable? Thread is a class Runnable is interface
Java supports only single inheritance Runnable is interface So it can be multiply inherited So, use Runnable when you have to inherit from some other class This is required for multithreading in applets
68
Dealing with Exceptions
Exceptions can arise from all sorts of sources the JVM detecting a fatal error the JVM recognizing a problem e.g., index bound a java object encountering an unusual condition e.g., file troubles, stack underflow The above fall into three categories of Throwable Error RunTimeException Exception Errors and RunTime Exceptions are unchecked. All other Exceptions are checked.
69
Checked Exceptions You must handle a checked exceptions, e.g., IOException explicitly. You either declare that you throw the exception public void useIO() throws IOException { … } Or, you catch the exception and handle as you see fit try { … } catch (IOException e) { … }
70
Multiple Exception Types
try { might throw exceptions … } catch (Exception1 e1) { handling exception of type Excetion1 … } catch (Exception2 e2) { handling exception of type Excetion2 … } catch (Exception3 e3) { handling exception of type Excetion3 … } finally { //always executed, even if no exception }
71
Exception Hierarchy
72
Organizing Classes Classes are the building blocks, but they can become very numerous and hard to manage Java provides two means for organizing classes – the file and the package Classes in the same file are tightly coupled, with only one allowed to be public – it’s name must match the file name (class Charlie must be stored in Charlie.java) second class must be inner Class: Classes can be embedded one deep The more scalable organizing is through packages – classes bonded by mutual trust
73
Packages The package name is usually in a dotted notation signifying its placement in a directory hierarchy. package com.imagesoft.image.utils; // stored in myclassbase/com/imagesoft/image/utils Packages partition name space, providing a means to prevent name collision.
74
Garbage Collection Most objects created by most programs have very short lives . Garbage Collection collect unused objects around for a while.
75
References “Object Oriented Programming” by Charles E. Hughes Available From [Accessed 30/ 08/ 2007] Java Software Solutions Foundations of Program sign Third Edition by John Lewis and William Loftus
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.