searbe

    • Edit
    • Delete
    • Tags
    • Autopost

    Java for PHP programmers

    I wanted to learn Java so I could get on with some Android programming. I’ll try to cover everything that someone who only knows PHP would need to know to get to grips with Java. Have a quick read of this and it’ll answer a few questions you might have along the way.

    Java is strongly typed

    Something you might not be used to is the concept of “declaring” a variable. In Java you must declare a variable first.

    DatabaseRecord foo;
    foo = new DatabaseRecord();

    On line 1 you declare the variable specifying its type (so the variable “foo” must contain a DatabaseRecord). On the next line, you create a new DatabaseRecord object and assign it to “foo”. You can do that all on one line:

    DatabaseRecord foo = new DatabaseRecord();

    So here once foo is declared, anything assigned to it must be of the type DatabaseRecord. You can only ever assign a DatabaseRecord to the variable “foo”. Whereas in PHP-land, you could put a string in a variable that was an object a second ago.

    So this is valid in PHP:

    $foo = new Bar();
    $foo = "Blah blah";

    But the equivalent is not valid in Java:

    DatabaseRecord foo = new DatabaseRecord();
    foo = "Blah blah";

    Even a method must have a return type specified:

    In PHP:

    class myClass {
        public function getName() {
            return "Craig";
        }
    }

    In Java:

    class myClass {
        public String getName() {
            return "Craig";
        }
    }

    Note you don’t specify “function”. For functions that don’t return a value or return with “return;”, use “void” in place of “String”

    Object properties are called fields

    In PHP you have “properties” in objects:

    class myClass {
        public $foo = 'bar';
        protected $_bar = 'baz';
    }

    In Java you have “fields”. The syntax is similar, and you must specify a type for each field.

    class myClass {
        public String mFoo = 'bar';
        protected String mBar = 'baz';
    }

    One convention I saw in an Android code sample was to prefix every property with ’m' (for ‘Member Field’). I find useful for identifying which variables are fields of the current object, especially taking the next point into account.

    You don’t use “this” very often

    When you’re accessing properties in Java, you don’t use “$this”.

    In PHP you’d go:

    class myClass {
        protected $_bar = 'baz';
    
        public function getBar() {
            return $this->_bar;
        }
    }

    In Java you wouldn’t use “this”:

    class myClass {
        protected String mBar = 'baz';
    
        public String getBar() {
            return mBar;
        }
    }

    The only time you really need to use “this” is if you have a collision and it becomes unclear which variable you mean. For example:

    In Java:

    class myClass {
        protected String mBar = 'baz';
    
        public String getBar(String mBar) {
            return this.mBar; // specify "this" to access the mBar field
                              // instead of the mBar that was passed to
                              // the method
        }
    }

    Annotations (e.g. @override)

    When you start overriding methods in parent classes, you’ll notice “@override” in front of methods that are overridden.

    I suppose you can think of this as a message to the compiler (the thing that turns your code into a program). The @override annotation denotes that following method overrides a method in the parent class. It won’t compile if it doesn’t.

    You can set up your own annotations for whatever reason you might like, and you can access information on what annotations are set on a specific method using Reflection (up next).

    Here’s a (rather pointless) example of the @override annotation:

    class MyActivity extends Activity {
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            return super.onCreateOptionsMenu(menu);
        }
    }

    See this guide for more info on annotations: http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

    Reflection – “What is Object.class?”

    Every class you declare essentially extends the Object class. The Object class will give your class a bunch of standard methods and fields. One of them is a static member accessed via ClassName.class. This will return you a “Class” object.

    This “class” object describes your object and has various methods for exploring your object – for example, you could use it to see what annotation a method has. Or you could use it to let another method know what class to create.

    You might see something like this:

    String someObject = "A string";
    Intent i = new Intent(someObject, MyActivity.class)

    This is creating a new “Intent” object, passing in the string object, then passing in the Class object from static MyActivity.class field. For instance, internally the Intent object might use the Class object to create a new MyActivity object – as the class object has a newInstance() method.

    Generics – Angled / Square Brackets in Java

    If you see this kind of syntax:

    List<Integer> = new LinkedList<Integer>();

    You might be confused by the angled brackets. These are “generics” and allow you to tell the List object what kind of object it will be storing.

    Set yourself some time aside to read this excellent tutorial: http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

    Arrays aren’t the solution any more

    In Java, you’re not going to find arrays as useful as you do in PHP. In PHP you declare an array without specifying any size, the type of the array, or anything.

    In Java, you have to specify the length of the array. And you can only have an array of one type of object (for example, it must contain all integers, or all strings).

    So in PHP:

    $stringArray = array('One', 'Two', 'Three');

    In Java:

    String[3] stringArray;
    stringArray[0] = "One";
    stringArray[1] = "One";
    stringArray[2] = "One";

    Note that you declare an array by putting square brackets containing the array length. Then you can access those three, and only those three elements.

    If you want a list of objects of unspecified size, you probably want to use a LinkedList object. The usage of that goes like this:

    LinkedList myList = new LinkedList();
    myList.add(new MyObject());
    myList.add(new MyObject());
    myList.add(new MyObject());

    That adds three MyObject objects to the list. The nicest way to iterate through a linked list is using for-each syntax, which is similar to PHP’s. Alternatively a for loop using myList.size() would work.

    To use a for-each as per below, you must iterate over something that implements the Collection interface. List and LinkedList both implement this interface, thus the following is possible:

    LinkedList myList = new LinkedList();
    myList.add(new MyObject());
    myList.add(new MyObject());
    myList.add(new MyObject());
    
    for (MyObject myobj : myList) {
        myobj.doSomething();
    }

    So that’s “for each (MyObject)myObj in myList, do this:”. The equivalent in PHP would be:

    $myList = array();
    $myList[] = new MyObject();
    $myList[] = new MyObject();
    $myList[] = new MyObject();
    
    foreach ($myList as $myObj) {
        $myObj.doSomething();
    }

    Personally I think Java’s way of doing it makes more sense. PHP’s way almost seems back-to-front.

    Associative Arrays

    For those moments where you absolutely must have an associative array, you use a hashtable.

    See the following documentation: http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html

    Note that you have to cast objects on the way out – the Hashtable doesn’t use the Generics mechanism I described earlier to ensure a specific data type.

    Implementing interfaces with anonymous objects

    Something I found really cool, and if you’ve used interfaces before I’m sure you will too, was implementing interfaces with anonymous objects. In PHP, if you have an interface, you need a solid class declaration somewhere that implements it, then you use that class declaration.

    In Java you can implement an interface on-the-fly. You specify the interface you’re implementing, followed by a code block containing the implementation:

    OnClickListener myClickListener = new OnClickListener() {
        public void onClick(DialogInterface dialoginterface, int i) {
            startGame(i);
        }
    };

    Neat huh? It’s really useful for tiny handler objects like the above. Imagine having to have a whole concrete class declaration for 50 handlers that are only used once anyway.

    Inner / Nested Classes and Interfaces

    In the example above I actually omitted something – the OnClickLister is actually a “static nested interface”. The correct code is this:

    DialogInterface.OnClickListener myClickListener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialoginterface, int i) {
            startGame(i);
        }
    };

    I will attempt to explain however I found the following the most useful piece of information: http://download.oracle.com/javase/tutorial/java/javaOO/nested.html

    The first example is a regular inner class (not a static one like the OnClickListener). You can have a class declaration inside a class, and only the outer class may ever create an instance of the inner class. That’s a “nested class” and it looks like this:

    class MyClass {
        class MyInnerClass {
        }
    
        public void foo() {
            MyClass.MyInnerClass innerObject = new MyClass.MyInnerClass();
        }
    }

    So you create an inner class declaration (MyInnerClass) that can only exist within the outer class (MyClass).

    Sometimes a class should live inside another class but still be accessible to the world – so it’s only living within another class for the sake on namespacing, like the OnClickListener example above (the difference being it’s an interface rather than a class, so you’d just substitute “class” with “interface”).

    In this case, you’d use the ‘static’ keyword:

    class MyClass {
        static class MyInnerClass {
        }
    
        public void foo() {
            MyClass.MyInnerClass innerObject = new MyClass.MyInnerClass();
        }
    }
    
    class MyOtherClass {
        public void foo() {
            MyClass.MyInnerClass inner = new MyClass.MyInnerClass();
        }
    }

    Note that in this case, the inner class can reside within another class entirely. It doesn’t have to be inside MyClass.

    • 22 December 2010
    • Views
    • Permalink
    • Favorited 0 Times

    Comments 0 Comments

    Leave a Comment

  • Craig Bendell's Posterous

    PHP developer living in Worthing, UK working for D3R. Starting Android / Java development for fun.

  • About Craig Bendell

    PHP developer living in Worthing, UK working for D3R. Starting Android / Java development for fun.

  • Subscribe

    Subscribe to this posterous
    Unsubscribe
    Subscribe via RSS
    You're a contributor here (Edit)
    This is your Space (Edit)
    Follow by email »
    Get the latest updates in your email box automatically.
    Follow on Twitter
  • Follow Me