Does JavaFX have Multiple Inheritance?

29 06 2009

CatDog cartoon from Nickodean

CatDog cartoon from Nickelodeon

Introduction

Often when we learn about object oriented programming we try to find out if a particular language contains a dirty little phrase called multiple inheritance. Of course there are good reasons to try to avoid it (Diamond Problem) but sometimes you can’t.  I believe that it can be used in certain contexts which can be done safely (fearing and trembling from angry purists). In Java when asked if multiple inheritance is supported the answer is “Well, Sort of” or “Yes, but…“. Java has interfaces which follows the Design by Contract concept which forces the developer to implement the interface methods. Fundamentally when we think of abstraction we think of what behavior is common across classes. Abstract classes help but tend to get bloated and some folks resort to creating NOP (No operation performed) methods. One of the major principles of object oriented programming is re-use not un-re-use while rendering an object very coupled-ygoop. It would be wonderful if you could have method re-use from an abstract data type. Well, JavaFX has this ability to do this very thing! So, to ask the question again “Does JavaFX have multiple inheritance?“. I would answer it like this: “Yes, its similar to Java’s Interfaces but with implementation details“. JavaFX uses a concept called Mixin classes which allows the developer to inherit multiple classes. Sweet!

Example

I couldn’t help but think about all kinds of cats when thinking about multiple inheritance (not to be confused with these types of cats I Can Has Cheezburger ). In a nutshell there are Big cats and Small cats.

Requirements:

  • Some Big cats can roar, but all big cats can’t meow.
  • Similarly small cats can meow, but all small cats can’t roar.
  • All cats can purr.

In this example we will model reusable behavior as Mixins and we will also create the standard abstract classes such as “Animal” and “Cat“.

Step 1: Create Abstract Classes

abstract class Animal {
    public var name:String;
    public function eat(food:String){
        println("munchin on {food}");
    }
}

abstract public class Cat extends Animal {
    public function purr(volume:Integer){
        println("Purrrr...level({volume})");
    }
    public function scratch(){
        println("Scratching...")
    }

}

Step 2: Create Mixin Classes

public mixin class Roarer {
    public var bass:Integer = 20;
    public function roar(){
        println("Roar...");
    }
}

public mixin class Meower {
    public var pitch:Integer = 5;
    public function meow(){
        println("Meow...");
    }
}

Step 3: Create Derived Classes Inheriting Mixin Classes

// Cheetah's can't roar and can't meow
class Cheetah extends Cat {
}

class Lion extends Cat, Roarer{
    public override var bass = 50;
    public override function roar() {
        println("(ROAR) I'm King of the land!!!");
    }
}

class HouseCat extends Cat, Meower {
    public override var pitch = 10;
    public override function meow(){
        println("Meow...");
    }
}

Step 4: Create instances of the types of Cats

var fluffy:Cat = HouseCat{name:'fluffy'}; // regular house cat
var simba:Cat = Lion{name:'Simba'};      // Lion King cat
var chester:Cat = Cheetah{name:'Chester'}; // Cheetos' Chester

var cats:Cat[] = [fluffy, simba, chester]; // cat bus

Step 5: Create a script level function

Cat will ask to come into your house. Notice the down cast to Meower and Roarer type cats.

function letMeIntoHouse(cat:Cat){
        print("LET ME IN! ");
        if (cat instanceof Meower){
            var meower = (cat as Meower);
            meower.meow();
        }
        if (cat instanceof Roarer){
            var roarer = (cat as Roarer);
            roarer.roar();
        }
        cat.scratch();
}

Step 6: run() function like Java’s main()

This will loop through a sequence of cats by:

  • Cat asking in your house
  • Introduces cat
  • Feeds cat
  • Cat will purr
  • function run(){
        def food:String = "tender vittles";
        for (cat:Cat in cats){
            letMeIntoHouse(cat);
            print("The cat named {cat.name} is ");
            cat.eat(food);
            cat.purr(5);
        }
    }

    Output

    LET ME IN! Meow...
    Scratching...
    The cat named fluffy is munchin on tender vittles
    Purrrr...level(5)
    LET ME IN! (ROAR) I'm King of the land!!!
    Scratching...
    The cat named Simba is munchin on tender vittles
    Purrrr...level(5)
    LET ME IN! Scratching...
    The cat named Chester is munchin on tender vittles
    Purrrr...level(5)

    Conclusion

    Although this example doesn’t use Mixins in an RIA context, instead its used with simple domain objects to show multiple inheritance. Hopefully we can now answer the question when asked, “Does JavaFX have multiple inheritance?“. Is it ever a quick answer?

    References:





    JavaFX Presentation Model Pattern Using Binding

    28 06 2009

    Introduction

    When working with Java Swing I used the JGoodies libraries such as Binding, Forms, Validation to build very cool Swing applications. So, this enabled me to soon learn the Presentation Pattern. The key advantages using the presentation pattern are to decouple the domain objects from the presentation layer, to help reduce complexity and facilitate multiple presentation layers. Some other advantages are ease of unit testing, functional testing (testing various layers independently of each other) and code maintenance (better package structuring).  Since JavaFX has binding for fweee (a line in the movie Bed Time Stories) do we still need to be concerned or understand this great pattern while using JavaFX? I believe we should. In my opinion I think people would likely get into trouble with the bind keyword without proper understanding of the presentation model pattern. Here I will demonstrate a simple form with a TextBox bound to a domain object in a bidirectional way. (written using JavaFX 1.2)

    Example

    There are two scenarios that will describe how data will flow. Scenario 1 is when a user is changing information on the view component and the data will be set on the domain object. Scenario 2 is when data is set in a domain object which intern will update the view component. In the application there will be a section called Variables which will display each variable or attribute being set.

    Scenario 1: Changing the View

    Enter Person Name

    Enter Person Name

    A GUI form contains a field allowing the user to type in the person’s name. As soon as the user loses focus or hits the Enter key the person object’s name is automatically populated.


    Scenario 2: Changing the Model

    Setting bean property

    Setting bean property

    A GUI form contains a second field allowing the user to type in the person’s name. As soon as the user hits the Enter key the person object’s name property will be modified which notifies the presentation model which updates the view (TextBox) component with the new name (text property).

    Presentation Model Pattern Demo – This is a simple test to demonstrate how we can mimic the presentation model pattern. Click image to launch.

    Presentation Model Pattern Demo

    Presentation Model Pattern Demo

    Step 1: Create domain object

    //Simple JavaFX bean class
    class Person {
        public var name:String
    }

    Step 2: Create presentation model

    // create presentation model
    var namePresentationModel:String on replace oldValue {
        println("Old Value = {oldValue}"); // debug code
        println("New Value = {namePresentationModel}"); // debug code
    }

    Step 3: Create a person object instance from the Person class
    By binding the presentation model with the person object’s name attribute and using inverse to bind the other way. Person.name notifies namePresentationModel which notifies personForm (TextBox see Step 4)

    // create an object instance of Person
    var personBean = Person{
        name: bind namePresentationModel with inverse
    };

    Step 4: Create view component (Person’s name TextBox)

    By binding the presentation model with the personForm(TextBox) ’s text attribute and using inverse to bind the other way. personForm (TextBox) notifies namePresentationModel which notifies Person.name. This is a JavaFX common profile TextBox component.

    // create the view or form (in this case just a textbox)
    // bidirectional binding to presentation model
    var personForm:TextBox = TextBox{
                    text: bind namePresentationModel with inverse
                    columns: 12
                    selectOnFocus: true
    }

    Step 5: Create a way to set the person bean’s name attribute
    The action executes when the user hits the enter key. This works only on the desktop profile. Notice below where the action function will set the personBean’s name attribute to the text entered into TextBox. This is a JavaFX common profile TextBox component.

    // create the view or form (in this case just a textbox)
    // This will manually set person.name to personForm2.text
    var personForm2:TextBox = TextBox{
                    text: ""
                    columns: 12
                    selectOnFocus: true
                    action: function(){
                        personBean.name = personForm2.text
                    }
    }

    Conclusion

    Although I have comments and debug statements you will notice how simple and very little code to achieve the presentation model pattern. In the near future I would bet that there will be JavaFX application frameworks which will make form type application development with ease. Any comments are welcome. Enjoy!





    JavaFX Init Block Setting Default Values

    26 06 2009

    Introduction

    To create default values in Java, an instance variable with a String data type we would often have null and empty string values by default. In JavaFX we can create default values the same, but also have the opportunity to determine if the instance variables have ever been initialized at all.  This is cool because you can ensure that values are valid before the values can be used. An example would be if you had a variable called distance which holds an Integer.  A distance could not be a negative so the init block implementer could ensure that anything less than zero will take on the value zero.  When using an init block, you can use JavaFX’s a built-in function called isInitialized(object:Object) located (javafx.lang.Builtins) to determine if the instance variable has been initialized.

    public static boolean isInitialized(java.lang.Object varRef)

    Example

    In this example a class called Cat will have instance variables called name and age. The default values will be initialized inside of the init block after the instance variables get their values.

    The Cat class’ requirements:

    • When the Cat is instantiated without values being set the values are considered null and not initialized. Name the cat ‘Felix’.
    • When the Cat is instantiated with values being set to null name the cat ‘Garfield’
    • When the Cat is instantiated with values being set to empty string name the cat ‘Tom’

    Example

    package initstuff;
    
    /**
     * @author cdea
     */
    class Cat {
        var name:String;
        init {
    
            // Default name setting when there are null or empty string values
            // Not initialized
            if (not isInitialized(name)){
                name = "Felix"
            } else {
                // Is initialized but with null or empty string as value
                if (name == null) {
                    name = "Garfield"
                } else if (name.trim().equals("")){
                    name = "Tom"
                }
            }
        } // init
    }
    
    var myCat = Cat{};
    println("myCat's name is {myCat.name}");
    var myCat2 = Cat{name:" "};
    println("myCat2's name is {myCat2.name}");
    var myCat3 = Cat{name:null};
    println("myCat3's name is {myCat3.name}");

    Output

    myCat’s name is Felix
    myCat2’s name is Tom
    myCat3’s name is Garfield

    Conclusion

    This is very similar to constructors in Java, but in JavaFX you have a little more control of setting the values after values have been initialized. This will help prevent the user of the API to put invalid information when instantiating an object. Another example is that it ensures the values fall in a particular range.





    JavaFX Init and Postinit Blocks Order

    25 06 2009

    Introduction

    I noticed in JavaFX there isn’t really the same kind of concept as a constructor in Java. I want to create an example that will show the order of the init block and postinit block execution when an object is instantiated. I created a super class (SuperClass) and a subclass (SubClass extends SuperClass) to see the order of init blocks and postinit blocks executed.

    This is the order the init and post init block run execution:

    1. Init block executes right after the attribute values are set or initialized.
    2. Postinit block executes right after the object is finished initialized.

    Example

    package initstuff;
    
    /**
     * This will simply display the order of init block order.
     * @author carldea
     */
    
    var x:Integer = count();
    
    function count():Integer {
       Main.x=Main.x+1;
    };
    
    class SuperClass{
       init {
          println("{x} SuperClass init block");
          count();
       }
       postinit{
          println("{x} SuperClass postinit block");
          count();
       }
    }
    
    class SubClass extends SuperClass{
       init {
          println("{x} SubClass init block");
          count();
       }
       postinit{
          println("{x} SubClass postinit block");
          count();
       }
    }
    
    var myJfxObject = SubClass{}

    Output

    1 SuperClass init block
    2 SubClass init block
    3 SuperClass postinit block
    4 SubClass postinit block





    JavaOne 2009 Woah, I know KungFu

    19 06 2009

    Introduction

    Woah, I know KungFu-Neo

    I’m sure folks have seen the movie “The Matrix” where in the scene when Neo is downloading all the fight training programs to his tiny brain. Well, that was my experience at JavaOne.  Ok, maybe I’m being overly dramatic, but you must understand how long I’ve been wanting to go to this conference. So, coming back from JavaOne I learned a great deal and I have been still digesting what I have learned. My main focus was desktop development and I was privileged to hang out with many great engineers from Sun and Authors of many books that I’ve only known virtually. Here are some photos during my time at the JavaOne 2009 Conference in San Francisco. I wish I had taken more photos, but its OK, I got a lot of videos with a very cool HD flip camcorder they gave me. Here are the many sessions and their slides that I have attended: Sun Developer Network / JavaOne / Java SE and Desktop However, I did get a chance to see and learn at least two server-side sessions too.

    One of my main goals as an avid Java person (thanks to my two daughters) was to learn and meet the people who are the pioneers of JavaFX.  Another highlight of the day (day 2) was I got a chance to meet James Gosling which was an honor and privilege.

    JavaOne Store

    (not to be confused with the Java App Store)

    One of the coolest things I’ve seen was the HTC diamond phone that was demonstrated and sold at the JavaOne Store. This is a full featured phone which contains Java ME/ JavaFX 1.2 which is demonstrated at Sergey Malenkov’s Blog. He has many JavaFX mobile apps demonstrated on the phone. I too bought this super duper cool phone. When I get some free time I will start playing with JavaFX mobile and blog about it.

    I was one of the lucky ones to buy other stuff at the JavaOne store. It was pretty busy because people were just trying to buy up everything Java, Java, Java from t-shirts, pens, dukes, etc. As if it was the last JavaOne we will ever see. Actually it would be the last Sun sponsored one we’ll ever see. (but good news here is Scott & Larry’s keynote) . I guess this indicates how many developer folks continue to love all things Java no matter the economic conditions. (Kathy Sierra’s Blog entry about the JavaOne Store on July 04, 2005).

    JavaOne Bookstore

    John Griffin writes “Top Ten at JavaOne” on The Server Side about the top selling books at the JavaOne Conference Bookstore. Which the top two are ones that I have bought. One book that is worth mentioning is the “Pro JavaFX™ Platform: Script, Desktop and Mobile RIA with Java™ Technology” which did not make it on the shelves that day, However I got a chance to meet all four authors (Weiqi Gao, Dean Iverson, Stephen Chin, James L. Weaver) at the JavaOne Bookstore for a book signing. I have the e-book and waiting for my hard copy to be delivered.

    1. JavaFX: Building Rich Internet Applications – Addison Wesley ISBN: 013701287X
    2. Essential JavaFX – PTR (out June 11, 2009) ISBN: 0137042795

    141-4109_IMG

    I am still reading both books and will have more examples to show, so stay tuned.

    Conclusion

    I was happy to come home, but sad that it was over so quickly. Coming out of JavaOne I felt that there was a huge sense of a new beginning and that JavaFX Script/platform will be what early Java was meant to be (truly cross platform). Just witnessing JavaFX 1.2 running on a mobile device, TV set-top box and the Desktop it simply tells me where the future of JavaFX will eventually move towards.  As consumers demand better user experiences and richer content I believe that Java/Sun was very wise to move in this direction. I can only hope that Oracle will embrace this technology and come out strong to compete with other RIA technologies.