software engineering methods written by: zvi avidor for the c++ programmer thanks to oleg pozniansky...
Post on 15-Jan-2016
216 views
TRANSCRIPT
Software engineering methods
Written By:
Zvi Avidor
for the c++ programmer
Thanks to Oleg Pozniansky for his comments
Why Java ?
• Object Oriented
• New (1995)
• Easy to learn
• Many additional features integrated inside:
Security, JDBC, GUI, MT, Communication.
JVM
• JVM stands for
Java Virtual Machine• Java “executables” are executed on a CPU
that does not exist.
JVM (Cont)C++
file1.cpp
file2.cpp
file1.obj
file2.obj
compilation
main.exe
link
CPU1
CPU2 main.exefile1.obj
file2.obj
execute
Imm
ediate
sources
JVM (Cont)Java
File1.java
File2.java
Main.java
sources
compilation
File1.class
File2.class
Main.class
Executeon CPU1
Executeon CPU1
java Main
java Main
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)
More sophisticatedpublic 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 !!!
Primitive TypesType Size Minimum Maximum Literals Default*
boolean - - - true, false false
char 16-bit Unicode 0 Unicode 216-1 'x' '\u0000'
byte 8-bit -128 +127 (byte)1 (byte)0
short 16-bit -215 +215-1 (short)1 (short)0
int 32-bit -231 +231-1 1, 0754, 0xfe
0
long 64-bit -263 +263-1 1L 0L
float 32-bit IEEE754 IEEE754 1.2f 0.0f
double 64-bit IEEE754 IEEE754 1.2 0.0d
void - - - - -
* Default values are guaranteed only for class members
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
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
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++:
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}
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
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
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
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); }}
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
6a
1
6a
2b{
b=a}
Garbage collection (Cont)
6a
2b
{ Number b=a;}
6
1
Out ofscope
6
0
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
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”);
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 theClass.Only one instance of ‘x’exists in memory
Output:
1510
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
• 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
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 packagestatement is the entire source file. package p1;
public class C1 {...}class C2 {...}
C1.java
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
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();
• Importing an entire package– Use the import statement with the asterisk (*) wildcard
character:import p1.*;...C1 myObj = new C1();
– Name disambiguationimport p1.*; // contains class C1import p2.*; // contains another C1 class
... C1 myObj = new C1(); // ambiguity error p1.C1 myObj = new p1.C1(); // OK
Using Package Members (Cont)
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
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
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
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!
CLASSPATH (Cont)
• Windows command promptset CLASSPATH=dir1;dir2;...;dirN
• Unix CShellsetenv CLASSPATH dir1:dir2:...:dirN
• Unix Bashexport CLASSPATH=dir1:dir2:...:dirN
• java, javac –classpath flag (Unix version)java –classpath dir1:dir2:...:dirN Rectangle
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(); // ERRORC3 c3 = new C3(); // ERROR
}}
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.
Access Control - cont.
Base
Derived
Package P1
Package P2
SomeClass
prot
ecte
d public
SomeClass2
private
Friendl
yInheritance
Usage
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
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
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 }}
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()• ...
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 mustbe an abstract class
Example
Example: Abstract Classespackage 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
• 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
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) { … }
}
When to use an interface ?
Perfect tool for encapsulating the inner structure of classes. Only the interface is exposed.
final
• final member dataConstant 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() { }}