Génie Logiciel et Gestion de Projets. Object-Oriented Programming An introduction to Java - PDF

Description
Génie Logiciel et Gestion de Projets Object-Oriented Programming An introduction to Java 1 Roadmap History of Abstraction Mechanisms Learning an OOPL Classes, Methods and Messages Inheritance Polymorphism

Please download to get full document.

View again

of 73
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
Information
Category:

Crafts

Publish on:

Views: 18 | Pages: 73

Extension: PDF | Download: 0

Share
Transcript
Génie Logiciel et Gestion de Projets Object-Oriented Programming An introduction to Java 1 Roadmap History of Abstraction Mechanisms Learning an OOPL Classes, Methods and Messages Inheritance Polymorphism 2 History of Abstraction Mechanisms Abstraction Abstraction is the purposeful suppression, or hiding of some details of a process or artifact, in order to bring out more clearly other aspects, details and structure. 4 History of Abstraction Mechanisms The function centered view Functions and Procedures The data centered view Modules Abstract Data Types The service centered view Object-Oriented Programming 5 Abstraction Mechanisms in OOP languages Classes are as ADTs in a service-centered view Message Passing and Method binding bring polymorphism leading to more readable code Class Hierarchies and Inheritance bring code sharing resulting in increased functionality and reduction of code size. Inheritance and Polymorphism together allow for tailoring shared code. 6 Parnas Principle For modules: One must provide the intended user with all the information needed to use the module correctly and nothing more One must provide the implementor with all the information needed to complete the module and nothing more For objects: A class definition must provide the intended user with all the information necessary to manipulate an instance of a class correctly and nothing more. A method must be provided with all the information necessary to carry out its given responsibilities and nothing more. 7 Learning an OOPL Class definition is like a type definition specifies the data and the behavior (methods) to be associated with this data, does not create a value (object); default values for data can be specified; visibility of data and behavior can be specified Object instantiation the creation of a new instance of a class, i.e. a value (object) initial values for the data fields can be passed 9 Messages have a receiver (the object the message is sent to), a message selector (some text indicating the message being sent), and arguments. Class hierarchies are defined when in a class definition one or more parent classes can be specified (single multiple inheritance) Inheritance is the property that instances of a child class or subclass can access both data and behavior (methods) associated with a parent class or superclass Method binding or method look-up is a mechanism for determining the method to be used in response to the message being sent 10 Classes, Methods and Messages Card Example A card belongs to a suit, has a rank and a color. A card can be face up or face down on the table (screen) and can be flipped from one position to the other A card can be displayed upon and erased from the screen A magic card is a special kind of card, its rank can be changed 12 Class Definition Card suit: {diamond, club, heart, spade} rank : integer faceup : boolean color : {red, black} Flip() some code Draw(W : Window, X : Position, Y : Position) some code Erase() some code Define Class name data definitions method declarations and definitions define class: Card... 13 Java (version 5) Java is not a dialect of C++, there are superficial surface similarities but the underlying differences are substantial. Java does not have pointer, reference, structure, and union types, goto statement, function definition or operator overloading. Java uses garbage collection for memory management, introduces the concept of interfaces, introduces packages and package visibility, supports multithreading and exception handling. Java is a portable language due tot he use of a virtual machine. 14 Java Card class class Card { final static public int red = 0; final static public int black = 1; final static public int spade = 0; final static public int heart = 1; final static public int diamond = 2; final static public int club = 3; // static values private boolean faceup; // data fields private int rankvalue; private int suitvalue; public Card (int sv, int rv){ // constructor suitvalue = sv; rankvalue = rv; faceup = true; } 15 Java Card Class (cont d) public boolean isfaceup(){ return faceup; } // access attributes public int rank(){ return rankvalue; }; public int suit(){ return suitvalue; }; public int color(){ if (suit() == heart suit() == diamond) then return red; else return black;} public void flip() { faceup =! faceup; }//actions public void draw( Graphics g, intx, int y) }; } 16 Visibility Visibility modifiers to control visibility thus manipulation of data fields and methods Public features can be seen and manipulated by anybody (external/interface/service view) public void flip(){ faceup =!faceup;} Private features can be manipulated only within class (internal/implementation view) private int suitvalue; 17 Constructor A constructor is a function that is implicitly invoked when a new object is created. In Java a constructor is a function with the same name as the class. public Card (int sv, int rv){// constructor suitvalue = sv; rankvalue = rv; faceup = true;} 18 Getter and Setters Getter and setter methods (or accessors and mutators) to control how data is accessed and modified. public boolean isfaceup(){ return faceup;} public int rank(){ return rankvalue;} 19 Class Data Fields Class data fields that are shared in common amongst all instances public class CountingClass { private static int count; //shared by all CountingClass(){ count = count + 1; } static {count = 0;} public int getcount(){ return count; } 20 Constant Data Fields Constant or immutable data fields to guarantee no changes will occur. Notice how symbolic constants are defined in Java: final static public int heart = 1; final static public int diamond = 2; final static public int club = 3; static means that all instances share the same value, one per class. final means it will not be reassigned. 21 Class Methods Static methods which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in ClassName.methodName(args) You can also refer to static methods with an object reference like: instancename.methodname(args) but this is discouraged because it does not make it clear that they are class methods. Class methods cannot access instance variables or instance methods directly, they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to. 22 Enumerations new in Java 5 enum declaration defines a full-fledged class possibility to add methods and fields to enum type, implement interfaces. public enum Suit {CLUBS, DIAMONDS, HEARTS, SPADES} public class Card{ private final Rank rank; private final Suit suit;...} 23 public enum Planet { MERCURY (3.303e+23, e6), VENUS (4.869e+24, e6), EARTH (5.976e+24, e6), MARS (6.421e+23, e6), JUPITER (1.9e+27, e7), SATURN (5.688e+26, e7), URANUS (8.686e+25, e7), NEPTUNE (1.024e+26, e7), PLUTO (1.27e+22, 1.137e6); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } public double mass() { return mass; } public double radius() { return radius; } // universal gravitational constant (m 3 kg -1 s -2 ) public static final double G = E-11; } public double surfacegravity() { return G * mass / (radius * radius); } public double surfaceweight(double othermass) { return othermass * surfacegravity(); } 24 Interfaces An interface is like a class, but it provides no implementation. Later, another class can declare that it supports the interface, and it must then give an implementation. public interface Storing { void writeout (Stream s); void readfrom (Stream s); }; public class BitImage implements Storing { void writeout (Stream s) { //... } void readfrom (Stream s) { //...} }; 25 Java Classes and Methods There is no preprocessor or global variables. Symbolic values are created by declaring and initialising a data field with the keywords final and static. The keyword static used on data fields indicates that only one copy of the data field exists which is shared by all instances. The keyword static on a method indicates that this method exists even when no instance of the class exist. A Java program needs one class with a main static method. Method implementations must be provided directly in the class definition. The public and private keywords are applied individually to every instance variable and method definition. 26 Instantiation and Initialization makeinstance class initial values makeinstance (acard) Card suit: Diamond Diamond, 9, rank: 9 false faceup: false makeinstance color: red Card (acard) Spade, 4, true suit: Spade rank: 4 faceup: true color: black 27 Creation and Initialisation in Java Object values are created with the operator new; space is allocated on the heap, the pointers are always implicit. parentheses even if arguments are not necessary The syntax of the new operator requires the use of All variables of some object type are initially assigned the value null. Constructors in Java can call other constructors on the same class by using the keyword this; it allows to factor out common behavior PlayingCard acard; // simply names a new variable // next expression creates the new object acard = new PlayingCard(Diamond, 3); 28 Message Passing send message object message selector arguments Message passing is the dynamic process of asking an object to perform an action Messages have a receiver (the object the message is sent to), a message selector (some text indicating the message being sent), and arguments. card mycard = new card(hearts, 9) mycard.draw(win1,10,10) if(mycard.faceup?())... (acard) suit: Diamond rank: 9 faceup: false true color: red Flip() 29 Message Passing in Java Java is statically typed: requires the programmer to declare a type for each variable. The validity of a message passing expression will be checked at compile time, based on the declared type of the receiver. Inside a method, the receiver can be accessed by means of a pseudo-variable, called this. A message expression or data access within a method with no explicit receiver is implicitly assumed to refer to this. 30 Message Passing in Java class PlayingCard {... public void flip () { setfaceup(! faceup ); }... } class PlayingCard {... public void flip () { this.setfaceup(! this.faceup); }... } 31 Inheritance Roadmap Meanings of Inheritance Syntax to describe Inheritance Various forms of Inheritance Java modifiers and inheritance Java constructors and inheritance 33 Class Hierarchies Card suit: {diamond, club, heart, spade} rank : integer faceup : boolean color : {red, black} Flip() some code Draw(W : Window, X : Position, Y : Position) some code Erase() some code MagicCard ChangeRank(R: integer) some code Define Class name superclasses data definitions method declarations and definitions Define Class: MagicCard Card... 34 Practical Meaning Data members defined in the parent are part of the child. Behaviour defined in the parent is part of the child. The child is an extension of the parent: The behaviour of a child class is strictly larger than the behaviour of the parent. The child is a contraction of the parent The child class can override behaviour to make it fit a specialized situation. 35 Java Syntax Subclasses are declared using the keyword extends class TablePile extends CardPile {... }; All classes are derived from a single root class Object; if no superclass is mentioned, Object is assumed class CardPile extends Object {... }; class CardPile {... }; 36 Substitutability The type given in a declaration of a variable may not match the type associated with a value the variable is holding. Substitutability through interfaces class CannonWorld extends Frame{... private class FireButtonListener implements ActionListener{ public void actionperformed(actionevent e){...} } public CanonWorld(){... fire.addactionlistener(new FireButtonListener());}} 37 Subtype and subclass A type B is considered to be a subtype of A if an instance of B can legally be assigned to a variable declared as type A. this value can then be used by the variable with no observable change in behavior. Subclass merely refers to the mechanism of constructing a new class using inheritance. It is not possible in Java to distinguish both concepts. 38 Specialised forms of Inheritance Specialization Specification Construction Generalisation or Extension Limitation Combination 39 Specialization The child class is a specialised form of the parent class but satisfies the specifications of the parent class completely. It creates a subtype. Is an ideal form of inheritance, good designs should strive for it. Window Move() Resize() TextWindow Edit() 40 Specification special case of inheritance for specialization guarantees that classes maintain a certain common interface implementation is deferred to child classes Java supports this idea through interfaces abstract classes and methods public abstract class Number{ public abstract int intvalue(); public abstract long longvalue(); public abstract float floatvalue(); public abstract double doublevalue(); public byte bytevalue(){ return (byte) intvalue();} public short shortvalue(){ return (short intvalue();} } 41 Construction the child class gets most of its desired functionality from the parent class only changing names of methods or modifying arguments forms subclasses that are not subtypes Example in Java Library: class Stack extends Vector{ public Object push(object item) {addelement(item); return item;} public boolean emtpy() {return isempty();} public synchronized Object pop() {Object obj = peek(); removeelementat(size() - 1); return obj;} is a fast and easy route to new data abstractions } public synchronized Object peek() {return elementat(size() - 1);} 42 Extension Example in Java Library: child class only adds behaviour to the parent class and does not modify or alter any of the inherited attributes subclasses are always subtypes class Properties extends Hashtable{... public synchronized void load(inputstream in) throws IOException{...} public synchronized void save(outputstream out, String header{...} public String getproperty(string key) {...} } public Enumeration propertynames(){...} 43 Limitation The behaviour of the subclass is smaller or more restrictive than the behaviour of the parent class. are not subtypes forms subclasses that occurs most frequently when building on a base of existing classes Suppose(!) Set class implemented like Vector class: class Set extends Vector{ //methods addelement, // removeelement, contains, //isempty and size are all //inherited from Vector public int indexof(object obj) {throw new IllegalOperation( indexof ); } public int elementat(int that should not, or index) {throw new cannot, be modified. IllegalOperation( elementat ); } Ragnhild Van Der Straeten - ULB - Génie logiciel et gestion } de projets / Combination multiple inheritance ability to inherit from two or more parent classes no multiple inheritance in Java approximations are possible e.g. new class extends an existing class and implements an interface e.g. new class implements multiple interfaces. Java library: RandomAccessFile implements both the DataInput and DataOutput protocols 45 Java Visibility Modifiers A private feature can be accessed only within the class definition (but memory is still found in the child class, just not accessible). class definition. A public feature can be accessed outside the A protected feature can be accessed only within the class definition in which it appears or within the definition of child classes. 46 Java Modifiers and Inheritance Static data fields and methods are inherited but static methods cannot be overriden. Methods and classes can be declared abstract. Abstract classes cannot be instantiated. An abstract method must be overridden in subclasses. The modifier final used with a class indicates that the class cannot be subclassed; the modifier final used with a method indicates that the method can not be overriden. 47 Inheritance and Constructors The constructor of a child class will always invoke the constructor for the parent class. This invocation always takes place before the code of the constructor is executed. If the constructor for the parent class needs arguments, the pseudovariable super is used as if it were a function. If no call on super is made explicitly, the default constructor (the one with no arguments) is used. class DeckPile extends CardPile { DeckPile (int x, int y, int c) { super(x,y); //initialise parent... //initialise child }...} }; 48 Benefits of Inheritance Software Reusability and Code sharing: when behavior is inherited from another class the code does not have to be rewritten saves time, reduces size and increases reliability Consistency of Interface: when many classes inherit from the same superclass it is easier to guarantee that interfaces to similar objects are indeed similar 49 Mechanisms for Software Reuse The two most common mechanisms for software reuse are composition and inheritance The has-as relationship between two concepts holds when the one is a component of the other but the two are not in any sense the same thing The is-a relationship between two concepts holds when the one is a specialised instance of the other Common sense helps most of the time: a car has an engine a dog is a mammal a car is an engine an engine is a car a dog has a mammal a mammal has a dog 50 Composition and Inheritance: the gray area List List Length() Member() Length() Member() Set Add(E : Element) Size() Set elements : List Add(E : Element) Size() Member() 51 Composition To reuse an existing data abstraction a portion of the state of the new data type is to be an instance of the existing structure using the operations of the existing data type the two data types are entirely distinct Operations on the new data type are implemented There are absolutely no claims on substitutability; Composition can exist in both object oriented and non-object oriented languages; the only significant difference between languages is in how the encapsulated data abstraction is created and initialised 52 Inheritance To reuse an existing data abstraction the new data type is declared to be a subclass of the existing class Operations on the existing data type are inherited by the new data type; the new class can add data values and add or override operations Inheritance carries the implicit assumption that subclasses are in fact subtypes; the instances of the new abstraction react similarly as the instances of the existing abstraction Proper creation and initialisation of the parent abstraction is language dependent 53 Composition and Inheritance Contrasted (1) Composition is simpler; what operations are supported by the data type is clear from the declaration only Through inheritance the operations of the new data type are a superset of the operations on the original data type; two or more declarations must be inspected to know the complete set (the yo-yo again) Data abstractions constructed through inheritance are briefer, the implementations are shorter Inheritance does not prevent users from manipulating the new data type with old operations breaching the information hiding principle leaving the values unprotected 54 Composition and Inheritance Contrasted (2) In composition the existing data type becomes a storage mechanism for the new data type and thus just an implementation detail. It is easier to reimplement the data type with another technique with minimal impact on the users of the data type Understandability and maintainability are difficult to judge. Inheritance has the advantage of brevity of code but the programmer must understand both classes. Composition code, although longer, is the only code the programmer must understand 55 Method Binding In a statically typed language we say the class of the declaration is the static c
Related Search
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks