1 © Luxoft Training 2012 Java & C++ compared Module #2.

Презентация:



Advertisements
Похожие презентации
Unit II Constructor Cont… Destructor Default constructor.
Advertisements

Operator Overloading Customised behaviour of operators Chapter: 08 Lecture: 26 & 27 Date:
© Luxoft Training 2013 Annotations. © Luxoft Training 2013 Java reflection / RTTI // given the name of a class, get a "Class" object that // has all info.
Inner Classes. 2 Simple Uses of Inner Classes Inner classes are classes defined within other classes The class that includes the inner class is called.
Data Types in C. A Data Type A data type is –A set of values AND –A set of operations on those values A data type is used to –Identify the type of a variable.
1/27 Chapter 9: Template Functions And Template Classes.
1/30 Chapter 8: Dynamic Binding And Abstract classes.
© Luxoft Training 2013 Java Collections API. © Luxoft Training 2013 Collections hierarchy.
Loader Design Options Linkage Editors Dynamic Linking Bootstrap Loaders.
A class is just a collection of variables--often of different types--combined with a set of related functions. The variables in the class are referred.
1 © Luxoft Training 2012 Inner and anonymous classes.
2005 Pearson Education, Inc. All rights reserved. 1 Object-Oriented Programming: Interface.
11 BASIC DRESS-UP FEATURES. LESSON II : DRESS UP FEATURES 12.
Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Welcome to…. YOUR FIRST PART – START TO FINISH 2.
© 2002 IBM Corporation Confidential | Date | Other Information, if necessary © Wind River Systems, released under EPL 1.0. All logos are TM of their respective.
Учимся писать Эссе. Opinion essays § 1- introduce the subject and state your opinion § 2-4 – or more paragraphs - first viewpoint supported by reasons/
1 When And How To Make Interfaces Work For You Advanced OO Techniques Alex Herbstritt Principal Software Engineer, Progress Software Session 102.
Data Variable and Pointer Variable Pass by Reference Pointer Arithmetic Passing Array Using Pointers Dynamic Allocation.
Arrays Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Транксрипт:

1 © Luxoft Training 2012 Java & C++ compared Module #2

2 © Luxoft Training 2012 Some Similarities between C++ and Java Simple (primitive) types: int, double, char Control Structures if-else, switch, while, for Language syntax Arithmetic expressions Both have a string type: C++ string, Java String. Arrays Both use classes. Both use "main".

3 © Luxoft Training 2012 class Entity { protected: char *name; int x,y; public: Entity(); ~Entity(); void setName(char *inName); void setXY(int inX, int inY); }; Entity::Entity() { x=y=0; name=NULL; } Entity::~Entity() { … } Entity::setName(char *iName) { … } Entity::setXY(int inX, int inY) { … } class Entity { protected String name; protected int x; protected int y; public Entity() { x=y=0; name=null; } public void finalize() { … } public void setName(String name) { … } public void setXY(int inX, int iny) { … } } C++ classJava class

4 © Luxoft Training 2012 Default values for arguments C++ allows default values for arguments of a function/method. Java does not. However, method overloading can be used to obtain similar results in Java: void methodA (int value) { // we need it to be default to 10 //... } void methodA () { this.methodA(10); } The minimum of code you need to compile for C++ is a function. The minimum for Java is a class.

5 © Luxoft Training 2012 Data conversions C++ allows a range of implicit conversions between native types (including some narrowing conversions), and also allows the programmer to define implicit conversions involving user-defined types: struct X { // implicit conversion operator int() const { return 7; } // explicit conversion explicit operator int*() const { return nullptr; } In Java, only widening conversions between native types are implicit; other conversions require explicit cast syntax. class TBase {}; class TChild extends TBase {}; TBase tbase; TChild tchild = (TChild) tbase; // only explicit cast TBase tbase2 = tchild; // implicit widening casting TBase TChild

6 © Luxoft Training 2012 C++: a choice of parameter types. Java: no choice of parameter types. C++: Call-by-value void f(int n); C++: Call-by-reference void f(int& n); Other C++ variants: void f(const int& n); void f(const int n); Java: All primitive type parameters are automatically call-by-value. public void f(int n) {...} Java: All class types are automatically something very much like call-by- reference. public void f(String n) {...}

7 © Luxoft Training 2012 Pass by value and by reference For passing parameters to functions, C++ supports both pass-by-reference and pass-by- value: void AddOne(int &y) // y is a reference variable { y = y + 1; } In Java, primitive parameters are always passed by value. Class types, interface types, and array types are collectively called reference types in Java and are also always passed by value. The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java. The key to understanding this is that something like Dog myDog; is not a Dog; it's actually a pointer to a Dog. What that means, is when you have Dog myDog = new Dog("Rover"); foo(myDog); you're essentially passing the address of the created Dog object to the foo method.

8 © Luxoft Training 2012 Java: no change of parameter of primitive type is possible public void change(PetRecord r) { r.name = "FooFoo"; } This really changes its PetRecord argument. public void change(int n){ n = 42; } This does not change its int argument. There is no way to write a Java method that has a parameter for an int variable and that changes the value of an argument variable.

9 © Luxoft Training 2012 Data types size Java built-in types are of a specified size and range defined by the language specification. In C++, a minimal range of values is defined for built-in types, but the exact representation (number of bits) can be mapped to whatever native types are preferred on a given platform. For instance, Java characters are 16-bit Unicode characters, and strings are composed of a sequence of such characters. C++ offers both narrow and wide characters, but the actual size of characters is platform dependent, as is the character set used. Strings can be formed from either type. This also implies that C++ compilers can automatically select the most efficient representation for the target platform (i.e., 64bit integers for a 64bit platform), while the representation is fixed in Java, meaning the values can either be stored in the less-efficient size, or must pad the remaining bits and add code to emulate the reduced-width behavior.

10 © Luxoft Training 2012 Pointers In C++, pointers can be manipulated directly as memory address values. Java references are pointers to objects. Java references do not allow direct access to memory addresses or allow memory addresses to be manipulated with pointer arithmetic. In C++ one can construct pointers to pointers, pointers to ints and doubles, and pointers to arbitrary memory locations. Java references only access objects, never primitives, other references, or arbitrary memory locations.

11 © Luxoft Training 2012 Function pointers In C++, pointers can point to functions or member functions (function pointers). // Pointer to functions int add(int first, int second) { return first + second; } int subtract(int first, int second) { return first - second; } int operation(int first, int second, int (*functocall)(int, int)) { return (*functocall)(first, second); } int main() { int a, b; int (*plus)(int, int) = add; int (*minus)(int, int) = subtract; a = operation(7, 5, plus); b = operation(20, a, minus); cout << "a = " << a << " and b = " << b << endl; return 0; }

12 © Luxoft Training 2012 Using interface implementation as function pointers The equivalent mechanism in Java uses object or interface references. interface Operation{ int op(int op1, int op2); } // we need to call some function int operation(Operation op, int a, int b) { return op.op(a, b); } void add (int a, int b) { Operation op = new Operation() { public int op(int a, int b) { return a+b; } }; operation(op, a, b); } // Java 8 only void addJava8(int a, int b) { operation((op1, op2)->op1+op2, a, b); }

13 © Luxoft Training 2012 Strings in Java Java string type is called String. Java strings are immutable, i.e. once created, their value cannot be changed: String s = "hello"; s = s+"!"; // s is a new object To change values StringBuilder should be used: StringBuilder sb = new StringBuilder(s); sb.append("!"); String result = sb.toString(); Java strings are objects, i.e. like every other type, the String type extends the Object type. Java Strings are using String pool String s1 = "hello"; String s2 = new String("hello"); Java strings keep textual information in 2-byte Unicode. String have to be compared only with equals(): if (s1 == s2) {} ; // false if (s1.equals(s2)) {}; // true

14 © Luxoft Training 2012 Strings concatenation in Java

15 © Luxoft Training 2012 Operator overloading C++ features user-defined operator overloading. Operator overloading allows for user-defined types to support operators (arithmetic, comparisons, etc.) like primitive types via user-defined implementations for these operators. It is generally recommended to preserve the semantics of the operators. Java does not support any form of operator overloading (although its library uses the addition operator for string concatenation).

16 © Luxoft Training 2012 Generics and annotations Java has generics, whose main purpose is to provide type-safe containers. C++ has compile-time templates, which provide more extensive support for generic programming and metaprogramming. Basically in C++ templates are basically a preprocessor/macro set. In Java they are basically syntactic sugar to minimize boilerplate casting of Objects. C++ templates have some features that Java Generics don't: Use of primitive type arguments. Use of default type arguments Java allows to do bounding of arguments: C++ templates with different arguments are different types. They don't even share static members. In Java this is not true – instead the template type is replaced by Object type. Java has annotations, which allow adding arbitrary custom metadata to classes and metaprogramming via an annotation processing tool.

17 © Luxoft Training 2012 Destructors There are no destructors in Java. There is no "scope" of a variable per se, to indicate when the objects lifetime is ended – the lifetime of an object is determined instead by the garbage collector. There is a finalize( ) method thats a member of each class, something like a C++ destructor, but finalize( ) is called by the garbage collector and is supposed to be responsible only for releasing "resources" (such as open files, sockets, ports, URLs, etc). If you need something done at a specific point, you must create a special method and call it, not rely upon finalize( ). Put another way, all objects in C++ will be (or rather, should be) destroyed, but not all objects in Java are garbage collected. Because Java doesnt support destructors, you must be careful to create a cleanup method if its necessary and to explicitly call all the cleanup methods for the base class and member objects in your class.

18 © Luxoft Training 2012 Single-rooted hierarchy Java uses a singly-rooted hierarchy, so all objects are ultimately inherited from the root class Object. In C++, you can start a new inheritance tree anywhere, so you end up with a forest of trees. In Java you get a single ultimate hierarchy. This can seem restrictive, but it gives a great deal of power since you know that every object is guaranteed to have at least the Object interface. C++ appears to be the only OO language that does not impose a singly rooted hierarchy.

19 © Luxoft Training 2012 Copy constructor In Java, copy constructor is not called implicitly like they are in C++: Now C++ will implicitly call the copy constructor with a statement like this: Cloning/copying in that instance simply makes no sense in Java because all b1 and b2 are references and not value objects like they are in C++. In C++ that statement makes a copy of the object's state. In Java it simply copies the reference. The object's state is not copied so implicitly calling the copy constructor makes no sense.

20 © Luxoft Training 2012 Style Comparison C++/Java Java uses loooong names: e.g. FileNotFoundException while C++ uses some abbreviations Java spelling conventions: ClassName, variableName, methodName, LITERAL_NAME Java has an official commenting style: javadoc