Presentation is loading. Please wait.

Presentation is loading. Please wait.

Software engineering methods Written By: Zvi Avidor for the c++ programmer Thanks to Oleg Pozniansky for his comments.

Similar presentations


Presentation on theme: "Software engineering methods Written By: Zvi Avidor for the c++ programmer Thanks to Oleg Pozniansky for his comments."— Presentation transcript:

1 Software engineering methods Written By: Zvi Avidor for the c++ programmer Thanks to Oleg Pozniansky for his comments

2 Why Java ? Object Oriented New (1995) Easy to learn Many additional features integrated inside: Security, JDBC, GUI, MT, Communication.

3 JVM JVM stands for Java Virtual Machine Java “executables” are executed on a CPU that does not exist.

4 JVM (Cont) C++ file1.cpp file2.cpp file1.obj file2.obj compilation main.exe link CPU1 CPU2 main.exe file1.obj file2.obj execute Immediate sources

5 JVM (Cont) Java File1.java File2.java Main.java sources compilation File1.class File2.class Main.class Execute on CPU1 Execute on CPU1 java Main

6 Hello World public class Hello { public static void main(String[] args) { System.out.println(“Hello World !!!”); } } Hello.java C:\javac Hello.java C:\java Hello ( compilation creates Hello.class ) (Execution on the local JVM)

7 More sophisticated public 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

8 Results javac Kyle.java ( to compile ) java Kyle ( to execute ) Kyle: You bastards !!!

9 Primitive Types TypeSizeMinimumMaximumLiteralsDefault* boolean---true, falsefalse char16-bitUnicode 0Unicode 2 16 -1'x''\u0000' byte8-bit-128+127(byte)1(byte)0 short16-bit-2 15 +2 15 -1(short)1(short)0 int32-bit-2 31 +2 31 -11, 0754, 0xfe 0 long64-bit-2 63 +2 63 -11L0L float32-bitIEEE754 1.2f0.0f double64-bitIEEE754 1.20.0d void----- * Default values are guaranteed only for class members

10 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

11 Case Sensitivity 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

12 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.

13 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.

14 Comments C++ Like: // bla bla.. /* this is a bla bla */ And Javadoc Comments: /** comment */

15 Flow control It is like C/C++: if/else do/while for switch if(x==4) { // act1 } else { // act2 } int i=5; do { // act1 i--; } while(i!=0); int j; for(int i=0;i<=9;i++) { j+=i; } char c=IN.getChar(); switch(c) { case ‘a’: case ‘b’: // act1 break; default: // act2 }

16 Reference Variables Every variable in Java (almost…) is a reference/pointer. C++ 5 9 a b MyObject *x ( not initialized !!!) Java MyObject x a=b MyObject x(5) Since we’re handling pointers, the following is obvious : 5 9 a b N/A

17 Testing Equality The equality operator == returns true if and only if both its operands have the same value. –Works fine for primitive types –Only compares the values of reference variables, not the referenced objects: Integer i1 = new Integer("3"); Integer i2 = new Integer("3"); Integer i3 = i2; i1 == i1 && i1 != i2 && i2 == i3 This expression evaluates to true

18 Object Equality To compare between two objects the boolean equals(Object o) method is used: –Default implementation compares using the equality operator. –Most Java API classes provide a specialized implementation. –Override this mehtod to provide your own implementation. i1.equals(i1) && i1.equals(i2) This expression evaluates to true

19 Example: Object Equality public class Name { String firstName; String lastName;... public boolean equals(Object o) { if (!(o instanceof Name)) return false; Name n = (Name)o; return firstName.equals(n.firstName) && lastName.equals(lastName); }

20 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 : Garbage Collection 6 a 1 6 a 2 b { b=a }

21 Garbage collection (Cont) 6 a 2 b { Number b=a; } 6 1 Out of scope 6 0 Garbage Collector

22 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

23 String is an Object Constant strings as in C, do 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”);

24 Static 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_); Assignment performed on the first access to the Class. Only one instance of ‘x’ exists in memory Output: 1 5 10

25 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

26 Static (Cont) Usage: TeaPot tp1 = new TeaPot(Color.RED); TeaPot tp2 = new TeaPot(Color.GREEN); System.out.println(“We have “ + TeaPot. howManyTeaPots()+ “Tea Pots”);

27 Packages A package physically and logically bundles a group of classes –Classes are easier to find and use (bundled together) A package is an abstraction of classes –Avoid naming conflicts –Control access to classes Unrestricted access between classes of the same package Restricted access for classes outside the package

28 Creating a Package place a package statement at the top of the source file in which the class or the interface is defined. –A default package is implicitly declared The scope of the package statement is the entire source file. package p1; public class C1 {...} class C2 {...} C1.java

29 Using Package Members Only public package members are accessible outside the package in which they are defined. –Refer to a member by its long (qualified) name A qualified name of a class includes the package that contains the class Good for one-shot uses –Import the package member When only a few members of a package are used –Import the entire package May lead to name ambiguity

30 Using Package Members (Cont) Refer to a package member by its qualified name: p1.C1 myObj = new p1.C1(); Importing a package member –Place an import statement at the beginning of the file, after the package statement: import p1.C1;... C1 myObj = new C1();

31 Importing an entire package –Use the import statement with the asterisk (*) wildcard character: import p1.*;... C1 myObj = new C1(); –Name disambiguation import p1.*; // contains class C1 import p2.*; // contains another C1 class... C1 myObj = new C1(); // ambiguity error p1.C1 myObj = new p1.C1(); // OK Using Package Members (Cont)

32 Managing Source and Class Files Source code is placed in a text file whose name is the simple name of the single public class or interface contained in that file and whose extension is.java Example: Rectangle.java

33 Managing Source and Class Files When you compile a source file, the compiler creates a different output file for each class and interface defined in it. –The base name is the name of the class or interface. –The extension is.class

34 Managing Source and Class Files.class files should be placed in a series of directories that reflect the package name. –Not necessarily in the same directory as the sources. –Placed by the compiler when the –d flag is specified. Example: javac –d classes Rectangle.java

35 CLASSPATH Classes are searched for and loaded by both the java compiler (javac) and interpreter (java). The CLASSPATH is an environment variable that contains an ordered list of directories (or Zip files) in which class files are searched. –Contains top level directories in which package directories appear. –By default, CLASSPATH is set to the current directory. In most cases there is no need to change this default!

36 CLASSPATH (Cont) Windows command prompt set CLASSPATH=dir1;dir2;...;dirN Unix CShell setenv CLASSPATH dir1:dir2:...:dirN Unix Bash export CLASSPATH=dir1:dir2:...:dirN java, javac –classpath flag (Unix version) java –classpath dir1:dir2:...:dirN Rectangle

37 Access control public class –‘new’ is allowed from other packages ( default: only from the same package (note: not necessarily from the same file) ) package P1; public class C1 { } class C2 { } package P2; class C3 { } 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 }

38 Access Control - cont public member (function/data) –Can be called/modified from outside. Protected –Can be called/modified from derived classes private –Can be called/modified only from the current class Default ( if no access modifier is stated ) –Usually referred to as “Friendly” or "Package access". –Can be called/modified/instantiated only from within the same package.

39 Access Control - cont. Base Derived Package P1 Package P2 SomeClass protected public SomeClass2 private Friendly Inheritance Usage

40 Inheritance Base Derived class Base { Base(){} Base(int i) {} protected void foo() {…} } class Derived extends Base { Derived() {} protected void foo() {…} Derived(int i) { super(i); … super.foo(); } As opposed to C++, it is possible to inherit only from ONE class. Pros avoids many potential problems and bugs. Cons might cause code replication

41 Polymorphism Inheritance creates an “is a” relation: For example, if B inherits from A, than we say that “B is kind of 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

42 Inheritance Example 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 }

43 Everything is an Object All classes implicitly inherit from the class java.lang.Object –Root of the class hierarchy. –Provides methods that are common to all objects (including arrays). boolean equals(Object o) Object clone() int hashCode() String toString()...

44 Abstract Classes 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 an abstract class Example

45 Example: Abstract Classes 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... }

46 Interface Defines a protocol of communication between two objects Contains declarations but no implementations –All methods are public –All fields are public, static and final (constants). Java’s compensation for removing multiple inheritance. You can implement as many interfaces as you want. Example

47 Interface interface SouthParkCharacter { void curse(); } interface IChef { void cook(Food); } interface Singer { void sing(Song); } class Chef implements IChef, SouthParkCharacter { // overridden methods MUST be public // can you tell why ? public void curse() { … } public void cook(Food f) { … } }

48 When to use an interface ? Perfect tool for encapsulating the inner structure of classes. Only the interface is exposed.

49 final final member data Constant member final member function The method can’t be overridden. final class ‘Base’ is final, thus it can’t be extended final class Base { final int i=5; final void foo() { i=10; } class Derived extends Base { // Error // another foo... void foo() { }


Download ppt "Software engineering methods Written By: Zvi Avidor for the c++ programmer Thanks to Oleg Pozniansky for his comments."

Similar presentations


Ads by Google