1 / 93

A Quick Intro to Java for C and C++ Programmers

A Quick Intro to Java for C and C++ Programmers. Scott Hudson HCI 631 Fall 2000. About this lecture. Will be assuming you are a fluent C or C++ programmer. This is going to be a quick introduction to the language. I'm not going to teach anything much about object-oriented programming. .

sherise
Download Presentation

A Quick Intro to Java for C and C++ Programmers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. A Quick Intro to Java for C and C++ Programmers Scott Hudson HCI 631 Fall 2000

  2. About this lecture • Will be assuming you are a fluent C or C++ programmer. • This is going to be a quick introduction to the language. • I'm not going to teach anything much about object-oriented programming.

  3. What is Java • Java is a programming language designed by James Gosling at Sun • Designed to be "squirted" across a network into a device, the primary device right now being a web browser • Interpreted from byte codes (virtual machine approach) • Dynamically loaded • => very portable (except...)

  4. What is Java • "A pretty good object oriented language with C++ camouflage on" • Once was "The latest thing" and massively hyped

  5. Why was there hype about Java? • At the right place at the right time (important need on the web) • (Supposed to be) Highly portable (finally is) • Seen by lots of companies as a way to break the Microsoft monopoly (didn’t work) => huge amounts of money involved => major corporate politics/warfare (Sun & Netscape vs. Microsoft)

  6. Beyond the Hype (and loss thereof) • Not much fundamentally new here • we have seen almost all the concepts in other languages before • But, its fairly well designed • more than can be said for a lot of things • Its better than C++ for many/most uses • It was built by someone who knew the "landscape" of programming languages and has some taste

  7. Beyond the Hype (and loss thereof) • In my opinion its the best current language with wide platform support (backing of many solid implementations)

  8. Goals • Downloadable into a wide range of devices/platforms • Good OO language to replace C++ • Relatively small/simple/clean language • Camouflaged as C++ for sneak attack when C++ was the dominant language • C++ programmers will feel at home • Lots of checking and safety

  9. Major differences from C++ • Generally simplified • No pointers • Actually everything is a pointer (reference), but their are no dangling pointers! • No pointer dereferencing (where you used to say "->" you now always use ".") • Garbage collection added • Big big win

  10. What's been added from C (all in C++) • O-O concepts & information hiding • Stronger typing • Real constants (not just macros) • Overloading (two functions with the same name, but different parameter types) • New comment style ("//" to eol)

  11. What's been added beyond C++ • More checking • Exceptions (they were in C++, but..) • (Limited) signature based typing ("interfaces" -- a big win) • Runtime type identification (plus other reflection capabilities) • Built in threads and synchronization

  12. What's been added beyond C++ (cont.) • Packages (collections of classes in a namespace) • Dynamic runtime loading • Strings (as objects) • A root class (Object) • Unicode characters (16 bit chars) • 64 bit longs, bytes, booleans • (literals true and false)

  13. What's been added beyond C++ (cont.) • A (small) container library (hashtables, etc.) • Special "doc" comments /** ... */ + post-processing to produce hyperlinked API documentation • html + special @directives in the comments

  14. Things that are missing (but we probably won't miss): • Virtual functions (everything is virtual!) • Virtual base classes • Virtual destructors • Implicit constructor invocation (and other constructor/destructor weirdness)

  15. Things that are missing (but we probably won't miss): • Arcane type conversion rules (and generally loose typing) • 16 different meanings for const • extern (now have strong load-time checking) • ->* operator (member pointers) • :: (scope operator)

  16. Things that are missing (but we probably won't miss): • void * • Null terminated strings • Declaration vs. definition (always done together, need not declare before use) • (Brain dead) multiple inheritance • Templates

  17. Things that are missing (but we probably won't miss): • Operator functions • Macros, include files, and conditional compilation (the preprocessor)

  18. Other things that are missing (that we might miss): • Independent functions • Pointers to functions • Default parameters • Unsigned types • Bare metal performance(?)

  19. So is it too slow? • Can get roughly 4x of C code performance (on many things you care about) using JIT compilers • Plenty fast for interactive apps • Spend a lot of time in native drawing code anyway • Faster development time => more optimization time => faster code!

  20. More details on differences with C++ Lexical level • Designed to look almost exactly like C++ (which is almost identical to C) • Minor differences, but not worth mentioning

  21. More details on differences with C++ Syntactic level • Designed to look a lot like C++ • which was designed as a superset of C • but cleaned up most egregious parts • Changes: • inheritance syntax • initialization in constructors • split definition vs. declaration (and scope operator) • protection declaration

  22. More details on differences with C++Control Flow • All C/C++ flow control constructs except goto • added labeled break and continue to handle the few remaining legit uses • if/else for while do/while switch/case/break • return break continue • throw try/catch/finally to support exceptions

  23. Exception syntax try { … throwable except = new my_exception(); throw(except); … } catch (my_exception ex) { … do something to recover … } catch (Exception ex) { … } finally { … code that is always executed … }

  24. More details on differences with C++Control Flow (cont.) • Now have real booleans • can't test integers and pointers directly • "if (ptr)" must be "if (ptr != null)"

  25. Classes • The major construct in Java (like most object oriented languages) is the class. • Classes are a type definition: They define the data and operations of an object. • You can create several instances of objects; several things with that data and those operations

  26. Classes • For C programmers you can think of this for now as a struct with the functions operating on the struct "inside" the struct. • For C++ programmers you can think of this as a class.

  27. class point_list { int x; int y; point_list next; double distance_to(point_list other) { double dx, dy; dx = (double)(x - other.x); dy = (double)(y - other.y); return Math.sqrt(dx*dx + dy*dy); } double distance_to_next() { if (next == null) return 0; else return distance_to(next); } }

  28. What have we got here. • Three instance variables • C++ == fields • Two methods • C++ == member functions • Note: There are no functions in Java, just methods (notice that we had to say Math.sqrt() to get a square root).

  29. What have we got here. • If we had two points: pt1 and pt2, then we could compute the distance between them as pt1.distance_to(pt2) • Except... we have some problems here what are they? (p, v, c, after)

  30. Problem #1: self containment • Looks like a point_list contains a point_list class point_list {... point_list next; • But, recall everything is a pointer, so this is a pointer (reference) to a point_list, so we are ok

  31. Like C++ Two forms of data: primitive and objects Primitive types: byte 8 bit signed integer short 16 bit signed integer int 32 bit signed integer long 64 bit signed integer boolean true of false char 16 bit unicode character float single precision double double precision

  32. If its not a primitive its an object • Note: this includes strings & arrays • Declaring instance variables of object types actually declares references to objects of that class • null is a possible value • need to be initialized to refer to object • Referenced with “.” instead of “->” (back to problems)

  33. Problem #2: Visibility • Classes also provide information hiding and the default is to not allow full access to instance variables or methods. • So a better version would be...

  34. public class point_list { protected int x; protected int y; protected point_list next; public double distance_to(point_list other) { double dx, dy; dx = (double)(x - other.x); dy = (double)(y - other.y); return Math.sqrt(dx*dx + dy*dy); } public double distance_to_next() { if (next == null) return 0; else return distance_to(next); } }

  35. public protected private <unlabeled> Accessible to all Accessible to classes within the same package and subclasses Accessible only within the class itself Inside package: protected Outside package: private (no subclass access outside package). Specifying protection Members can be:

  36. Specifying protection Classes can be: • public, unlabeled, or private • Almost all classes are public (anybody can use them) • Can have private or local classes • only accessible in package • rare • can protect constructors instead

  37. Point of style • Its a good idea for all but the simplest classes to not have any public instance variables. • Instead have a protected variable with read and write access methods. • This lets you change your mind later without breaking all the code that uses yours.

  38. Point of style protected int _x; public int x() {return _x;} public void set_x(int val) {_x = val;} • Seems tedious, but… This has saved my sorry butt many times! (back to problems)

  39. Problem #3: no constructor • Haven't provided a way to create any useful objects of this type • Java initializes instance variables: int et al. 0 boolean false float, double 0.0 char ‘\0’ Object null

  40. Initialization • You can also explicitly initialize instance vars protected int x = 0; protected int y = 0; protected point_list next = null;

  41. Declaring constructors • Typically, you want provide a constructor. • If you don't provide a constructor, one (that does nothing and takes no parameters) will be provided for you. • Constructor looks like a method with the same name as the class but no return type:

  42. Declaring constructors public point_list( int xv, int yv, point_list nxt) { x = xv; y = yv; next = nxt; }

  43. Declaring multiple constructors • Often want to provide several constructors • Java does not do default parameters public point_list(int xv, int yv) { this(xv,yv, null); } public point_list() { this(0,0); }

  44. Declaring multiple constructors • Notice that we can "chain" constructors together using "this()". • We can also invoke the super class constructor using "super()". • Must be the first thing in the constructor. (back to problems)

  45. Some misc. basics • All parameters are pass-by-value. • However, for all object types we are passing references by values, so... • Can return at most one value. • Arithmetic, etc. operations (precedence, etc.) are the same as C/C++, except...

  46. Some misc. basics • Arithmetic, etc. operations are the same as C/C++, except... • Use of comma operator is limited to for statements. • Can apply bitwise operations to booleans (but not mixed int/boolean) to get non-shortcutting operations. • == and != mean "refer to the same object".

  47. Some misc. basics • Like C++ can declare variables anywhere a statement is legal • including inside parens of for statements • Same scoping rules • scope limited to enclosing block: {... } • Don't have to declare before use.

  48. Hierarchical Types and Inheritance • The big wins in object-oriented programming come from hierarchical typing and inheritance.

  49. Hierarchical Types and Inheritance • Two things of importance: • Inheritance: the ability to derive the implementation of something from some existing code (AKA getting someone else to do the work for you). • Substitutability: the ability to write code that doesn't care about exactly what type it operates over (so you can substitute related but different types).

  50. Inheritance • In Java (like most OO languages) you can base the implementation of a class on another class. • Basically, you take what is in the other class (the base or superclass) and then extend it to do new and/or different things. • The new class (the derived class or subclass) preserves the API of the superclass

More Related