800 likes | 949 Views
Software Engineering Methods Winter 2002-3. Lecture: Prof. Shmuel Katz. Teaching Assistants Adam Carmi Zvika Gutterman Grader Berliner Yaniv. Course Administration. Follow the web page: www.cs.technion.ac.il/~cs234321
E N D
Software Engineering MethodsWinter 2002-3 • Lecture:Prof. Shmuel Katz. • Teaching Assistants Adam Carmi Zvika Gutterman • GraderBerliner Yaniv
Course Administration • Follow the web page: www.cs.technion.ac.il/~cs234321 • Email: Use only the course e-mail! cs234321@cs.technion.ac.il • Grade: • test > 50 ? 0.6 HW + 0.4 Test : Test • Tests • Moed A - 07/Feb/2003 • Moed B - 07/Mar/2003
Time Table • Lecture: Sundays, 10:30-12:30 at Taub 2. • Group 11: Sundays, 14:30-15:30 at Taub 6. • Group 12: Tuesdays, 10:30-11:30 at Taub 3. • Group 13: Wednesdays, 14:30-15:30 at Taub 3. • Group 14: Cancelled !
Software engineering methods Java for the c++ programmer Written By: Zvi Avidor Additions: Adam Carmi Zvi Gutterman Thanks to Oleg Pozniansky for his comments
Reading • BooksIn Amazon: • 1662 Entries with Java … (03/2002) • 1918 Entries with Java … (10/2002) • Course Web Site. • Java.sun.com
Why Java ? • Object Oriented • New (1995) • Easy to learn • Many additional features integrated:Security, JDBC, GUI, MT, Communication, Documentation, … and lots more!
JVM • JVM stands forJava Virtual Machine • Unlike most other languages, Java “executables” are executed on a CPU that does not exist.
JVM - Cont. C++ execute compilation link file1.obj main.exe CPU1 Immediate sources file2.obj file1.cpp file2.cpp file1.obj main.exe CPU2 file2.obj
JVM - Cont. Java Execute on CPU1 sources java main file1.java file1.class compilation file2.java main.java file2.class main.class Execute on CPU1 java main
Primitive types • int 4 bytes • short 2 bytes • long 8 bytes • byte 1 byte • float 4 bytes • double 8 bytes • char Unicode encoding (2 bytes) • boolean {true,false} Behaviors is exactly as in C++
Primitive types - cont. • Constants • 37 integer • 37.2 float • 42F float • 0754 integer (octal) • 0xfe integer (hexadecimal)
Wrappers Java provides Objects which wrap primitive types and supply methods. Example: Integer n = new Integer(“4”); int m = n.intValue(); Read more about Integer in JDK Documentation
Hello World Hello.java class Hello { public static void main(String[] args) { System.out.println(“Hello World !!!”); } } ( compilation creates Hello.class ) (Execution on the local JVM) C:\javac Hello.java C:\java Hello
More sophisticated class Kyle { private boolean kennyIsAlive_; public Kyle() { kennyIsAlive_ = true; } public Kyle(Kyle aKyle) { kennyIsAlive_ = aKyle.kennyIsAlive_; } public String theyKilledKenny() { if (kennyIsAlive_) { kennyIsAlive_ = false; return “You bastards !!!”; } else { return “?”; } } public static void main(String[] args) { Kyle k = new Kyle(); String s = k.theyKilledKenny(); System.out.println(“Kyle: “ + s); } } Default C’tor Copy C’tor
Results javac Kyle.java ( to compile ) java Kyle ( to execute ) Kyle: You bastards !!!
Case Sensitive • Case sensitivity: • String is not the same as string • MAIN is not the same as main • Java keywords are all lower case • e.g. public class static void
Naming Conventions • Methods, variables and objects start with a leading lowercase letter : next, push(), index, etc. • Classes starts with a leading upper-case letter : String, StringBuffer, Vector, Calculator, etc.
Naming Conventions (2) • Constants (final) are all upper-case : DEBUG, MAX_SCROLL_X, CAPACITY. E.g. final double PI = 3.1415926; • Word separation in identifiers is done by capitalization, except for constants where underscore is used.
Comments • C++ Like:// bla bla ../* this is a bla bla */ • And JavaDoc Comments:/** comment */
Flow control It is like c/c++: do/while switch int i=5; do { // act1 i--; } while(i!=0); if/else char c=IN.getChar(); switch(c) { case ‘a’: case ‘b’: // act1 break; default: // act2 } If(x==4) { // act1 } else { // act2 } for int j; for(int i=0;i<=9;i++) { j+=i; }
Everything is a referenceto an Object Every variable in Java (almost…) is a reference/pointer. Java C++ MyObject x MyObject *x ( not initialized !!!) N/A MyObject x(5) Since we’re handling pointers, the following is obvious : a 5 a 5 a=b b 9 b 9
Garbage Collection • In C++ we use the ‘delete’ operator to release allocated memory. ( Not using it means : memory leaks ) • In Java there is no ‘delete’ and there are no memory leaks ! How could this be ? • answer : reference count b { b=a } 1 2 6 a 6 a
Garbage collection - cont. b Out of scope { Number b=a; } 2 6 a 1 0 6 6 Garbage Collector
Arrays • Array is an object • Array size is fixed Animal[] arr; // nothing yet … arr = new Animal[4]; // only array of pointers for(int i=0 ; i < arr.length ; i++) { arr[i] = new Animal(); // now we have a complete array
Arrays - Multidimensional • In C++ Animal arr[2][2] Is: • In Java Animal[][] arr= new Animal[2][2] What is the type of the object here ?
String is an Object • Constant strings as in C, does not exist. • The function call foo(“Hello”) creates a String object, containing “Hello”, and passes reference to it to foo. • There is no point in writing : • The String object is a constant. It can’t be changed using a reference to it. String s = new String(“Hello”);
Static Assignment performed on the first access to the Class. Only one instance of ‘x’ exists in memory • Member data - Same data is used for all the instances (objects) of some Class. Class A { public static int x_ = 1; }; A a = new A(); A b = new A(); System.out.println(b.x_); a.x_ = 5; System.out.println(b.x_); A.x_ = 10; System.out.println(b.x_); Output: 1 5 10
Static – cont. • Member function • Static member function can access only static members • Static member function can be called without an instance. Class TeaPot { private static int numOfTP = 0; private Color myColor_; public TeaPot(Color c) { myColor_ = c; numOfTP++; } public static int howManyTeaPots() { return numOfTP; } // error : public static Color getColor() { return myColor_; } } Example
Static - cont. Usage: TeaPot tp1 = new TeaPot(Color.RED); TeaPot tp2 = new TeaPot(Color.GREEN); System.out.println(“We have “ + TeaPot.howManyTeaPots()+ “Tea Pots”);
Packages • Java code has hierarchical structure. • The environment variable CLASSPATH contains the directory names of the roots. • Every Object belongs to a package ( ‘package’ keyword) • Object’s full name contains the full name of the package containing it.
Packages – After compilation When compiling the -d option defines the target root F:\MyClasses\P1\C1.class F:\MyClasses\P2\C2.class package P1; public class C1 { } package P2; public class C2 { } Directories are automatically created F:\MyClasses\P3\A\B\C1.class F:\MyOtherClasses\P1\C3.class package P3.A.B; class C1 { } package P1; class C3 { }
F:\MyClasses\P1\C1.class F:\MyOtherClasses\P1\C1.class F:\MyClasses\P3\A\B\C1.class F:\MyClasses\P2\C2.class Packages - Example, cont. Assume that CLASSPATH=F:\MyClasses;F:\MyOtherClasses Error !! C1 c=new C1(); P1.C1 c=new P1.C1(); import P1.*; C1 c=new C1(); import P3.A.B.C1; import P1.*; C1 c=new C1();
Access control public class • ‘new’ is allowed from other packages ( default: only from the same package (note: not necessarily from the same file) ) package P3; import P1.*; import P2.*; public class DO { void foo() { C1 c1 = new C1(); C2 c2 = new C2(); // ERROR C3 c3 = new C3(); // ERROR } } package P1; public class C1 { } class C2 { } package P2; class C3 { }
Access Control - cont • publicmember (function/data) • Can be called/modified from outside. • Protected • Can called/modified from derived classes • private • Can called/modified only from the current class • Default ( if no access modifier stated ) • Usually referred to as “Friendly”. • Can called/modified/instantiated from the same package.
Access Control - cont. Package P1 Package P2 private Base protected public SomeClass Derived Friendly SomeClass2 Usage Inheritance
class Base { Base(){} Base(int i) {} protected void foo() {…} } class Derived extends Base { Derived() {} protected void foo() {…} Derived(int i) { super(i); … super.foo(); } } Inheritance Base Derived As opposed to C++, it is possible to inherit only from ONE class. Prosavoids many potential problems and bugs. Consmight cause code replication
Polymorphism • Inheritance creates an “is a” relation: For example, if B inherits from A, than we say that “B is also an A”. Implications are: • access rights (Java forbids reducing of access rights) - derived class can receive all the messages that the base class can. • behavior • precondition and postcondition
Inheritance (2) • In Java, all methods are virtual : class Base { void foo() { System.out.println(“Base”); } } class Derived extends Base { void foo() { System.out.println(“Derived”); } } public class Test { public static void main(String[] args) { Base b = new Derived(); b.foo(); // Derived.foo() will be activated } }
Abstract • abstract member function, means that the function does not have an implementation. • abstract class, is class that can not be instantiated. NOTE: Every class with at least one abstract member function must be abstract class Example
Abstract - Example package java.lang; public abstract class Shape { public abstract void draw(); public void move(int x, int y) { setColor(BackGroundColor); draw(); setCenter(x,y); setColor(ForeGroundColor); draw(); } } package java.lang; public class Circle extends Shape { public void draw() { // draw the circle ... } }
Interface • abstract “class” • Helps defining a “usage contract” between classes • All methods are public • Java’s compensation for removing the multiple inheritance. You can “inherit” as many interfaces as you want. Example * - The correct term is “to implement” an interface
Interface interface IChef { void cook(Food); } interface Singer { void sing(Song); } interface SouthParkCharacter { void curse(); } class Chef implements IChef, SouthParkCharacter { // overridden methods MUST be public // can you tell why ? public void curse() { … } public void cook(Food f) { … } }
When to use an interface ? Perfect tool for encapsulating the classes inner structure. Only the interface will be exposed
final final class Base { final int i=5; final void foo() { i=10; } } class Derived extends Base { // Error // another foo ... void foo() { } } • final member dataConstant member • finalmember functionThe method can’t be overridden. • final class‘Base’ is final, thus it can’t be extended
Collection Iterator ArrayList LinkedList ArrayMap Collections produces behavior implementation Set Map List TreeSet HashMap TreeMap HashSet
List import java.util.*; class ListTest { static void showCollection(Collection col) { Iterator it = col.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } static void showList(List lst) { for(int i=0;i<lst.size();i++) { System.out.println("" + i + ": " + lst.get(i)); } } public static void main(String[] args) { LinkedList ll = new LinkedList(); ArrayList al = new ArrayList(); ll.add("one");ll.add("two");ll.add("three"); al.add("one");al.add("two");al.add("three"); showList(ll);showCollection(ll); showList(al);showCollection(al); } } 0: one 1: two 2: three one two three 0: one 1: two 2: three one two three
Map import java.util.*; class MapTest { static void ShowMap(Map m) { Set s = m.entrySet(); Iterator it = s.iterator(); while(it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); // downcast System.out.println(entry.getKey() + "-->" + entry.getValue()); } } public static void main(String[] args) { TreeMap tm = new TreeMap(); HashMap hm = new HashMap(); tm.put(new Integer(1),"one");tm.put(new Integer(2),"two"); tm.put(new Integer(3),"three"); hm.put(new Integer(1),"one");hm.put(new Integer(2),"two"); hm.put(new Integer(3),"three"); ShowMap(tm); ShowMap(hm); } } 1-->one 2-->two 3-->three 3-->three 2-->two 1-->one
IO - Introduction • Definition • Stream is a flow of data • characters read from a file • bytes written to the network • … • Philosophy • All streams in the world are basically the same. • Streams can be divided (as the name “IO” suggests) to Input and Output streams. • Implentation • Incoming flow of data implements “Reader” • Outgoing flow of data implements “Writer”
Stream concepts Source Sink Filter
IO - Examples (1) Reading input by lines FileReader in = new FileReader(“CrimeAndPunishment.txt”)); String s; while((s = in.readLine()) != null) { System.out.println(s); }