Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
1 Object Oriented Programming in Java Doc. Ing. František Huňka, CSc. 2 Literature, Web Resources • Bartezcko K.: Podstawy programovania w Javie. Wydawnictwo PJWSTK 2002 • Dacotha M., Monk E., Keller P.J.: Java Potrzaski. Helion 2003 • Eckel, B.: Thinking in Java 3 Curriculum 1. Basic concepts, platforms, UML, class & instance, Java development, constructors. 2. Classes closer look, primitive & object data types, this, modifier final, class attributes, class methods, main method. 3. Composition & aggregation, overloaded constructors, packages, JAR files, import. 4. Control statements, if, if else, for, while, break, continue, switch, logical operators 5. Inheritance, information hiding, method overriding. 4 Curriculum 6. Polymorphism, abstract class, abstract method, interface 7. Arrays, class Register, Exceptions 8. Collections, basic classes, graphical user interface (GUI) Benefits of Object-Oriented Perspective • There are three main benefits: – Real world apprehension – Stability of design – Reusability (at the programming code level) 5 6 Real world apprehension • Object-orientation is close to our own natural perception of the real world. • The basic philosophy underlying object oriented programming is to make the programs as far as possible reflect that part of the reality they are going to treat. 7 Programming process as a m odeling process m odeling problem specific concepts abstraction phenomena referent system realized concepts (classes) abstraction objects (instances) model system 8 Components of modeling process • A phenomenon is a thing that has definite, individual existence in reality or in the mind; anything real in itself. • A concept is a generalized idea of a collection of phenomena, based on knowledge of common properties of instances (objects) in the collection. 9 Stability of design • Instead of focusing on the functionality of a system, the first step in the system’s development is to make a physical model of the real world with which the system is concerned. • This model then forms the basis for the different functions that the system may have. • Functions may later be changed, and new functions may be added without changing the underlying model. 10 Reusability – traditional approach • One well known problem with software development is being able to reuse existing software components when developing new ones. • The new component is often implemented by copying and modifying the existing component, but this means that it must be tested again. • More problems, however, is that the relations between the old and new components may be lost; if an error is detected in one, it must be corrected in both. Also changes to common parts of the system may have to be performed in both components. 11 Reusability – object oriented approach • Object-oriented programming languages have strong constructs for supporting incremental programming modification. • It is possible to define a new component as an incremental extension of an existing one, thus preserving the relations between the two components. • Most object oriented languages are based on the class/subclass mechanism (inheritance). 12 Reusability - disadvantages • The disadvantage of incremental modification is that the library of components reflects the historical development of the components. • In addition, the relations between components are mainly dictated by maximal code sharing, often conflicting with the modeling requirements. Fundamental means of organization for apprehending the real world • Identification of phenomena and their properties. The result of this is a number of singular phenomena characterized by a selected set of properties. The phenomena are singular since they have not been classified in terms of concepts. • Classification is the means by which we form and distinguish between different classes of phenomena. That is we form concepts. Having identified phenomena and their properties and concepts, we group similar phenomena and concepts. 13 Fundamental means of organization for apprehending the real world • Classification is often called a taxonomy. When classification is applied repeatedly, classification hierarchy may be obtained. • Composition. A phenomena may be understood as a composition of other phenomena. There are two basic types of composition: whole part composition and aggregation (reference composition). 14 15 Object oriented languages • Simula – dated back to 1967 • Smalltalk – introduced model-view-control mechanism • C++ • Beta • Self, Ada • Java 16 Java as a Technology • • • • • • Object oriented Platform independent Robust, dynamic and safe Multiprocess Support Component Software Development Distributed 17 Outline public class HelloWord { public static void main(String args[]) { //metoda main začíná provádění Java aplikace System.out.println( “Hello World” ); } // konec metody main } // konec třídy HelloWorld Program structure in Java javac HelloWorld.java Compilation - compilation java HelloWorld – interpret runs method main from the HelloWorld class Execution (Interpretation) 18 class Hello { //Method that does the work public void go() { System.out.println("Hello, world"); } /** * main method for testing outside BlueJ */ public static void main(String args[]) { Hello hi = new Hello(); hi.go(); } } Outline Java Object Application 19 class Hello Outline { // Method that does the work public void go() { System.out.println("Hello, world"); } /** * main method for testing outside BlueJ */ // public static void main(String args[]) //{ Hello hi = new Hello(); // hi.go(); } } Java Object Application in BlueJ 20 Platform Independent • Java Bytecode (files .class) is a compilation product of the source files, which is independent of computer architecture – Libraries java.awt.*, java.net.*, java.applet.* • Java Virtual Machine (JVM) – imaginative machine implemented by means of program emulation on real machine – Instruction packet, registers, stack, garbage collector Typical Development Environment in Javě Phase 1: Edit Phase 2: Compile Phase 3: Load Disk Program created and stored in .java file Compiler Disk Compiler creates bytecode, which is stored into .class file Class Loader Primary Memory Class loader reads .class file from disk and stores it into the memory Primary Memory Bytecode verifier validates the whole bytecode Editor Disk Phase 4: Verify Phase 5: Execute 21 Bytecode Verifier Java Virtual Machine Primary Memory JVM reads bytecode and translates it into machine code (interprets bytecode) 22 Sun Microsystem – 2 Basic Products • J2SE Runtime Environment (JRE) that provides: – libraries, Java virtual machine, and further components that are necessary for applet execution and application execution written in the Java language. • J2SE Development Kid (JDK) covers: – JRE plus row oriented development tools such as compilers, debugging programs, which are necessary for application and applet development. Java Programming Language • Java is generally usable, concurrent, strongly typed, object oriented language based on classes. Java language is normally compiled into byte-code sets of instructions and binary format defined in Java Virtual Machine specification. • Java virtual machine (JVM) is an abstract computer machine, which has a set of instructions and manipulates memory during the execution of the program. JVM is ported on different platforms and provides both hardware and operating system independence. 23 What is UML 1/2 • Unified Modeling Language – (UML) a standard language for specification, vizualization, creation, and dokumentation of the programing systems, in the same way also for business modeling and different not programming systems. • UML is most spread graphical representation chart for object oriented systems modeling. 24 What is UML 2/2 25 • UML represents a collection of the best engineering experience, which were successfully proven in huge and complex systems modeling. • UML mainly exploits graphical notation for expressing of the software project design. • Using UML helps project teams to communicate, examine potential design and check the software systems architecture design. Objectives of UML 1/2 1. Provide users with simple, expressive visual modeling language in order they could develop and change thoughtful models. 2. Provide mechanism for extension and further specification of the basic concepts. 3. Be independent on concrete programming language and created processes. 4. Provide a formal foundation for understanding modeling language. 26 Objectives of UML 2/2 5. Support high level development concepts such as cooperation, programming frameworks, patterns and components. 6. Integrate the best experience. 27 UML Diagrams Types1/2 • Each UML diagram is designed to allow developers and customers to have a view of software system from different perspectives and changing levels of abstraction. UML diagrams generally create visual model tools that include: 28 UML Diagrams Types • Use Case Diagram • Class Diagram • Interaction Diagrams – Sequential Diagram – Cooperation Diagram • State Diagram • Activity Diagram • Physical Diagrams – Component Diagram – Deployment Diagram 29 Class Diagram 1/2 30 • Class diagram models structure and contents of the classes, for which it uses designed elements such as – classes, packets and objects. This diagram displays association between classes. Further specification of association can be composition, inheritance and so on. 31 Class Diagram 2/2 Class name Customer -name -address -listOfOccupations +print() +bestPaidOccupation() +monthlyPaiments() Attributes Operations, methods association Order Customer -dateOfAcceptance -isPaid -number -price +print() +send() +wholePrice() -name -address -listOfOccupations +print() +bestPaidOccupation() +monthlyPaiments() * 1 cardinality 32 Class Point • data attributes (data members) – x, y coordinates • methods – move – toString (inherited from class Object) – create text representation of the object – print 33 public class Point { private int x; private int y; public void move(int dx, int dy) { x = x + dx; y = y + dy; } public String toString() { String t = "X: "+ x +" Y: "+y; return t; } public void print() { System.out.println(“Point coordinates: "+this.toString()); } } Outline Class Point 34 public class PointTest { public static void main(String[] args) { Point a = new Point( ); Point b; System.out.print(“Point a: “); a.print(); a.move(20 , 50); System.out.print(“Point a: “); a.print( ); b = a; b.print( ); System.out.print(“Point b: “); b.move(-100, -200); System.out.print(“Point a: “); a.print(); } } Point a: Point coordinates: X: 0 Y: 0 Point a: Point coordinates: X: 20 Y: 50 Point b: Point coordinates: X: 20 Y: 50 Point a: Point coordinates: X: -80 Y: -150 Outline Class PointTest a – receiver print() – message without parameters move(20 , 30) – message with parameters 35 Graphical Representation a b null x 0 y 0 36 Message • Message that are sent to objects are typically composed of receiver of the message, message selector (message name) and possible message parameters: System.out.println(“Printed text … “ + variable); receiver method parameters 37 Object encapsulation Object data attributes message method1 method2 method3 38 Object oriented notation receiver.message(possible parameters); resultObj = receiver.message(possible parameters); 39 Access and Modification Methods • access methods: – start with get (conventions) – getX() returns x coordinate • modification methods: – start with set (conventions) – setX(type new argument) – setX(int newValue) sets x to the new value 40 public class Point { private int x; private int y; public void print() { System.out.println(“Point coordinates: "+this.toString()); } public int getX() { return x; } public void setX(int x){ this.x = x; } public String toString() { String t = "X: "+ getX() +" Y: “ + getY(); return t; } public void move(int dx, int dy) { setX( dx + getX()); // x = x + dx; setY( getY() + dy); // y = y + dy; } } Outline Object Technology • In the object model of computation we work only with two possible operations with the objects. The first of them is name an object – when an object is assigned to the variable, by which it is accessible. • The second operation is so called sending a message. Message represents a request for operation execution (method) of the given object. A message can also contained parameters that represent so called forward data flow (in the message propagation direction) in the direction to the message receiver. 41 42 Object Technology • The result of sent message is execution of the code of one of the object’s methods, which accepted the message. The code of the executed method usually gives some result, which represents reverse data flow (in the direction from receiver of the message to the sender of the message). • Regarding to the possibility of code the results of the executed methods are not restricted only to single object attributes but it can be the whole objects. 43 Object Technology • Running object oriented program is created by a system of mutually communicating objects, which is managed primarily by a sequence of external events from interface of the program. • Main program can be e.g. created by only single object declaration and sending a message to the object. 44 Encapsulation • Advantage of encapsulation: – Programs can be tested by smaller parts – Encapsulation helps to get rid of a frequent mistake connected with shared access to the common data. – Internal data strukture can be changed without necessity to change object environment (change of the data attribute names) – Libraries of objects can be created by abstraction of the data types and it will be possible to reuse them in other applications. 45 Encapsulation – Data the program works with are protected and identified. So data protection and data identification is assured. – Encapsulation helps to separate interface – (visible part of object) from implementation (hidden part of object). 46 Encapsulation • From the object definition results that the object typically put together data and operation over the data in one inseparable whole with data protection. Data used to be connected with theit operations so tightly thast it is impossible to access them without their operations. • Self-identification – object itself knows what it is, so the memory containing objects contains information of the object’s structure too. Information Hiding External - Internal • Speaking about external information hiding we have into our mind that objects should not either access their local data directly nor the code of individual operations. Object should be seen as an entity that is impossible to see through. 47 Information Hiding External - Internal • Speaking about internal information hiding we have into our mind the fact that in the scope of inheritance the successors do not have access to the local data attributes of their ancestors as well as to the code of individual operations of their ancestors. • Object can be understood as dynamic entities, which emerge, create new objects and decline during the running of the application. 48 49 Allocation Memory Management • Problem of terminated objects is usually solved by a special program called garbage collector (clear the memory from declined objects). • Objects with no reference to them. 50 Initializing objects with constructors • Java requires a constructor call for each object that is created, which helps ensure that the object is initialized properly before it is used in a program – the constructor call occurs implicitly when the object is created. • In any class that does not explicitly include a constructor, the compiler provides a default constructor – that is, a constructor with no parameters. 51 Constructors • The constructor name is always identical with the class name whose objects it creates. • There are no return values with constructors. • In case defining more constructors they must differ number or type of parameters. 52 Constructors with Point Class • declaring one constructors we must declare all other types of constructors • we speak about constructor’s overloading – more constructors that differ in number or type of parameters 53 public class Point { private int x; private int y; // Constructor without parameters public Point() { // initialise instance variables x = 0; y=0; } // constructor with one parameter public Point(int c) { x = c; y = c; } // constructor with two parameters public Point(int x, int newY) { this.x = x; y = newY; } public String toString() { String t = "\nX: "+ getX() + " Y: “ + getY(); return t; } Outline Class Point 1/2 54 public void print() { System.out.println(“Point coordinates: "+this.toString()); } public int getX() { return x; } public int getY(){ return y; } public void setX(int x){ this.x = x; } public void setY(int y){ this.y = y; } public void setPoint(Point a){ //copy constructor x = a.x; y = a.y; } public Point getPoint(){ return this; } } Outline Class Point 2/2 55 public class PointTest { public static void main(String[] args){ Outline Class PointTest Point a, b, c; String t; a = new Point(); b = new Point(-10, 122); c = b.getPoint(); c.tisk(); if (b==c) t = “Yes identical"; else t = “No different”; System.out.println(“Comparison result of two objects: "+t); c.setPoint(a); // copy constructor a.print(); b.print(); c.print(); } } 56 Point with Name Attribute • to distinguish among different object we add next attribute with name • name – String • change: – add new constructor – method toString() – add access and modification methods for the new attribute 57 Outline public class PointName { private int x; private int y; private String name; Class PointName 1/2 public PointName() { x = 0; y=0; name=“not assigned"; } public PointName(int c) { x = c; y = c; name=“not assigned"; } public PointName(int x, int { this.x = x; this.y = y; } public PointName(int x, int { this.x = x; this.y = y; } y) name= “not assigned"; y, String jm) name= jm; public String toString() { String t = "\nName of Point: "+getName() + " X: “ + getX() +" Y: "+getY(); return t; } 58 public void print() { System.out.println(this.toString()); } public int getX() return x; } { public void setX(int x) { this.x = x; } public String getName(){ return name; } public void setName(String newName){ name = newName; } public void move(int dx, int dy) { setX(getX() + dx); setY(getY() + dy; } } Outline Class PointName 2/2 59 public class PointNameTest { public static void main(String[] args) { PointName a = new PointName(); PointName b = new PointName(12); PointName c = new PointName(100, 200); PointName d = new PointName(10, 20, "DDD"); PointName e; a.print(); b.print(); c.print(); d.print(); e = d; e.move(100, 200); d.print(); e.print(); } } Outline Class PointNameTest