objective-c for java programmers, part 1 - christian...

4

Click here to load reader

Upload: truongduong

Post on 06-Sep-2018

212 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Objective-C for Java Programmers, Part 1 - Christian …facstaff.cbu.edu/cmbaker/ECE484/Objective-C_for_Java... · 2011-06-28 · Objective-C for Java Programmers, Part 1 By David

Objective-C for Java Programmers, Part 1By David Chisnall

Date: Mar 12, 2010

Article is provided courtesy of Addison-Wesley Professional.

Return to the article

The design of Java was heavily inspired by Objective-C, but many people find learning Objective-C after Javato be a difficult challenge. In the first of a two-part series, David Chisnall, author of Cocoa ProgrammingDeveloper’s Handbook, looks at the similarities and differences in the semantics of the two languages.

Objective-C was created back in 1986, but was a very niche language for much of this time. The main backerwas NeXT, a company that shipped only 50,000 computers over the course of a decade, limiting thelanguage’s exposure considerably. When Apple bought NeXT, this started to change. Objective-C became theprimary language for development on the Mac, giving it somewhere up to around 5-10 percent of thedesktop application development market share. Objective-C wasn't the only supported development languageon OS X though, and a lot of developers used things that they were more familiar with. The iPhone, incontrast, did not support anything other than Objective-C for third-party development.

If you're coming to either platform from a Java background, then you might find the change daunting.Objective-C looks very different to Java. Fortunately, once you get past the syntax, the languages are quitesimilar, and you'll find that the transition is not as difficult as the syntax might imply.

A number of the Java designers had experience with Objective-C, including some who had worked with NeXTon the OpenStep specification. A lot of ideas in Java are lifted directly from Objective-C, or taken fromSmalltalk, which inspired both languages. That's not to say that everything is the same in Objective-C. Thereare some important differences, which I'll explore in this and the next article.

Language PhilosophiesObjective-C was designed to bring the encapsulation support that Smalltalk enjoyed to the C language. Oneof its designers described it as a hybrid language, with the square bracket syntax as a sign indicating thetransition from C code to 'object land.'

The goal of Java was to make a language that was usable by average programmers. This combined Smalltalk-like semantics with C++ syntax. The latter decision was made more for marketing reasons than technicalones. C++ had a large market share (and still does, for some strange reason), and it was easier to makedevelopers switch to a language that looked similar than one that looked different.

This, unfortunately, is the cause of some of the major problems for people switching to or from Javadevelopment. Java looks like C++, but behaves a lot more like Objective-C. Both Java and Objective-C haveSmalltalk-like semantics, while C++ adds Simula-like semantics to C. Going between Java and C++ involvesswitching between Smalltalk and Simula semantics, without any corresponding change in the syntax.

Going between C++ and Objective-C is easier; a change in syntax accompanies a change in semantics. Goingbetween Objective-C and Java is a little bit confusing. There is a large change in syntax but only a smallchange in the semantics.

The difference in goals is obvious in a few places. Java aims to be vaguely C-like and easy for C or C++programmers to learn, but doesn't mind breaking things when the C way of doing things is not ideal.Objective-C is a pure superset of C. Every valid C program is a valid Objective-C program. One of the maindesign goals for Objective-C was to produce a language for parceling up C libraries into easily reusablecomponents.

Page 2: Objective-C for Java Programmers, Part 1 - Christian …facstaff.cbu.edu/cmbaker/ECE484/Objective-C_for_Java... · 2011-06-28 · Objective-C for Java Programmers, Part 1 By David

Objective-C originally didn't come with much of a standard library. You were expected to use it with Clibraries. The OpenStep specification, designed by Sun and NeXT, is commonly used as a standard library forObjective-C now, with implementation such as Cocoa or GNUstep available on most platforms. Java didn'tmake it easy to reuse existing code, so it needed a comprehensive standard library from the start.

Objects and PrimitivesJava contains a small selection of primitive, or intrinsic, types. These are values that are not objects. This isone of the biggest semantic differences between Java and Smalltalk. In Smalltalk, primitive types are treated asobjects and transparently boxed by the compiler or virtual machine. In Java and Objective-C, they are explicit.

Java only has a small selection of primitive types; four kinds of signed integer, two kinds of (signed) floating-point value, Booleans, and characters. Objective-C has all of the primitive types that C supports. The core setis similar, but with some important differences. The first is that C only defines the minimum range for a type.A short in Java is always 16 bits. A short in C is usually 16 bits. An int in Java is always 32 bits. An int in C is16, 32, or 64 bits on platforms that exist today, may be 128 bits in the future, but is usually 32 bits onplatforms where you'll use Objective-C.

Objective-C inherits the typedef keyword from C and a lot of standard definitions. The stdint.h header, forexample, defines uint32_t and int32_t types, which are always unsigned or signed 32-bit integers on everyplatform that you might use.

One of the typedef 'd types that Objective-C provides as standard is BOOL, which should only be YES or NO.This is really a char (an octet, on most platforms), and there are various ways in which it may get a value thatis neither YES or NO.

Java and Objective-C share the same initialization rules for primitive types. If they are declared in an instancevariable (what Java calls a field) in an object, then they will be initialized to 0 when the object is instantiated.If they are local variables, then they will be initialized to an undefined value.

Technically, Objective-C does not define how objects are instantiated. Unlike Java, Objective-C does notdefine a memory model at all; it inherits it from C. Objects are, by convention, allocated with something thatwraps the C calloc() library function. On OS X, this wrapping is quite complex, but the end result is thatevery object you create will have uninitialized values set to 0.

One important difference is that Objective-C inherits all of the structured non-object types from C. In Java,everything is either an object or a primitive. In Objective-C, you also have structures, primitive arrays, andunions.

Cocoa uses a few structures in a number of places. These include things like NSPoint, which represents apoint in 2D space. Unlike objects, which are always passed by reference, structures are commonly passed byvalue. They are also a lot cheaper to create than real objects.

Files and Compilation UnitsBoth Objective-C and Java store source code in files (unlike Smalltalk and a lot of Lisp environments). In Java,there is no difference between a file and a compilation unit. Objective-C, unfortunately, inherits the horriblemess that is the C preprocessor. In Objective-C, a compilation unit is a source file and every other file thathas been included in it by the preprocessor.

Objective-C extends the C preprocessor slightly, adding a #import directive. This is similar to #include butprevents multiple inclusion. If you #import a file, then you will only get one copy of it in the currentcompilation unit, no matter how many times you #import it.

In Java, the closest equivalent is the import directive. This is very different; it specifies a namespace thatshould be used to resolve a class. The Objective-C equivalent is much simpler; it just includes the textcontent of the specified file.

The preprocessor adds a bit of flexibility to Objective-C. You get things such as conditional compilation and

Page 3: Objective-C for Java Programmers, Part 1 - Christian …facstaff.cbu.edu/cmbaker/ECE484/Objective-C_for_Java... · 2011-06-28 · Objective-C for Java Programmers, Part 1 By David

some primitive metaprogramming tools, but it's quite basic.

Object ModelsOne place where Objective-C and Java are very similar is the core object model. Both use a very close copy ofthe Smalltalk object model, although Java tries to confuse people by describing it in Simula terminology.

Objects are instances of classes in both languages, and classes have at most one superclass. In Java, everyobject is a subclass of Object. In Objective-C, there are no such requirements. There is an Object class, butmost classes in Cocoa inherit from NSObject instead. You can create new root classes, although it's notadvisable.

Because you can have multiple base classes, Objective-C introduces the id type to represent a pointer tosome kind of object. You can implicitly cast between any object type and id.

The type systems are also similar, but with some important differences. Both are type-checked at compiletime and have runtime type enforcement. That's about where the similarities end.

The difference can be seen in the terminology used to describe how you interact with objects. Objective-Cuses the Smalltalk terminology, talking about sending messages. Java talks about calling methods. Thedistinction is quite subtle. Sending a message in Objective-C usually results in a method being called.

The big difference is that an object chooses how it handles a message, while a method call is seen as a morestatic thing. Java actually does method lookup dynamically, but it tries to hide this from the programmer. InJava, when you call a method, you must have a reference to an object of a type that implements this method.You can fake this with explicit casts, but the language tries to discourage you from doing so.

In Objective-C, you can send any message to any object. The type checker in the compiler will give you awarning if it doesn't think the object understands the message, but you are free to ignore it. If the messagereceiver is typed as id, then it can receive any message.

This is very flexible and is also the cause of one of the most difficult to debug problems in Objective-C.Methods are identified by name, not by name and type. If you define two methods with the same name anddifferent argument types, then you may not get any errors[md]especially if they are defined in differentlibraries. When you send a message to an object, the compiler constructs a call frame based on the types forthe method definition that it can see.

Methods in Objective-C are compiled down to the equivalent of C functions with two hidden arguments: thereceiver and the selector (an abstract representation of the method name). These are called just like any Cfunction. If you define a method taking a structure as an argument, for example, and then call it with anobject as an argument, then the call frame will not have the structure that the callee expects. The result isstack corruption. Because the stack is corrupted, your debugger probably won't be able to tell you exactlywhat broke.

Objective-C uses a small runtime library to implement dynamic behavior, rather than a complete virtualmachine. Apple maintains one and the GNU project maintains another. In the GNU runtime, selectors havetype information associated with them, so it's possible to track this kind of problem. In the Apple runtime,they are just names so it is not.

To avoid this problem, Objective-C methods usually have long and descriptive names, including typeinformation.

Static BehaviorIn Java, classes can have static fields and methods. A static field is effectively equivalent to a file static in C;it's a variable that has the lifespan of the program but has its visibility restricted to the compilation unit inwhich it is declared (or the class, in Java). A static method is effectively a namespaced function.

Objective-C has functions inherited from C. There is no direct equivalent of a static method, however. Classes

Page 4: Objective-C for Java Programmers, Part 1 - Christian …facstaff.cbu.edu/cmbaker/ECE484/Objective-C_for_Java... · 2011-06-28 · Objective-C for Java Programmers, Part 1 By David

in Objective-C are real objects. You can take a pointer to a class just as you would with an object and send itmessages. This lets you do some quite interesting things that are difficult in Java. One example is having adictionary mapping from strings to classes and creating a new class depending on which string you parse.This is incredibly useful, for example, when parsing XML and wanting a different parser class for eachelement that you might parse.

Different SyntaxObjective-C and Java make radically different decisions in terms of syntax. Java was intended to beapproachable by C users and so adopts C-like syntax everywhere. Objective-C, being a superset of C, takesthe philosophy that all new semantics should be accompanied by new syntax.

SummaryIn this week's article, I've looked mainly at the high-level semantic differences between Objective-C and Java.Next week I'll take a closer look at the detailed semantic differences.

© 2011 Pearson Education, Inc. All rights reserved.800 East 96th Street Indianapolis, Indiana 46240