490 likes | 525 Views
Software engineering methods. Java. for the c++ programmer. Written By: Zvi Avidor. 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.
E N D
Software engineering methods Java for the c++ programmer Written By: Zvi Avidor 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 forJava Virtual Machine • 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
Hello World Hello.java public 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 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
Results javac Kyle.java ( to compile ) java Kyle ( to execute ) Kyle: You bastards !!!
Primitive Types * 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++: 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; }
Reference Variables 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
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 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
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 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 • 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. C1.java package p1; public class C1 {...} class C2 {...}
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();
Using Package Members (Cont) • 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
Managing Source and Class Files • Source code is placed in a text file whose name is the simple name of the singlepublic 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 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
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 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. 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 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 must be an abstract class Example
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 ... } }
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 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 inner structure of classes. Only the interface is 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