Showing posts with label OOP. Show all posts
Showing posts with label OOP. Show all posts

06 July 2011

Java Swing basics

In Java Swing system, below are a few basic concepts you need to understand:
  1. Everything appears on screen is basically a component. JComponent is the Swing superclass of all things that draw on screen. For example, JLabel is a built-in JComponent that displays little text string. What you usually do is to create components objects and install it onto screen or their container.
  2. Frames (JFrame) are the outermost components. A JFrame represents a single window. Each JFrame component has a "content pane" JComponent that contains all components in the frame. You can use frame.getContentPane() to get the content pane. Content pane uses a Layout Manager to size and position its components. Frame has a convenience add() and setLayout() that go to its content pane.
  3. Components are placed inside other components which form a nesting hierarchy from outer to inner components. And each container is behind the components it contains. Layout Manager sizes and places those components according to some 'policies' or 'intents' of the layout. Don't call setSize() yourself, the layout manager controls that! Instead, do call setMinimumSize(), setMaximumSize() or setPreferredSize(), to register a preference before the layout manager lays everything out (before calling pack() / setVisible()).
  4. Three basic layout manager: FlowLayout, BoxLayout, BorderLayout. Flow layout arranges components left-right, top-down like text. Box layout aligns components in a line, either vertically or horizontally. Border layout puts main content in the center and decorate with 4 things around the outsize -- north, south, east, west.
  5. Swing thread, or Event-dispatch thread, Composite pattern and Observer/Observable patterns basically form the underlying architecture of Swing GUI system.
  6. A common technique in Java GUI code is to use an anonymous inner class to create a 'listener' class object and register it using addXXXListener() method to a Observable, e.g a button, on the fly.

17 March 2011

[Techonote] Java container anomaly

You can assign a pointer of type sub to a pointer of type super (this is simply a is-a relationship). However, you cannot assign a pointer type container(sub) to a pointer of type container(super) (e.g. List<String> IS NOT a List<Object>).

22 February 2011

[Technotes] Java Inner classes

First thing first, there is some terminology that needs to be explained.

In Java, you can define a class inside another class; such a class is called nested class. Nested classes can be divided into two categories: static or non-static. Static nested classes are simply called static nested classes. Non-static nested classes are called inner classes.

As for nested classes' privileges, inner classes have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class, instead, it can only access to static methods and members of the enclosing (parent) class.

To make the story even more complex, there are 2 other flavors of 'inner classes': local classes and anonymous classes (also called anonymous inner classes). You get to see lots of these two special kinds of inner classes in GUI codes. So you must understand and master them to be able to do GUI programming in Java. To see some concrete examples of these two classes, check out here and there.

In addition, you'd better read the following three web pages carefully before using inner or nested classes:

http://bit.ly/fPoJad - Nested classes introduction
http://bit.ly/dQzVvD - Inner class code example

Finally, to instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

31 January 2011

Virtual function

In object-oriented programming, a virtual function or virtual method is a function or method whose behaviour can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of OOP.

The purpose of having a virtual function is as follows:

In OOP when a derived class inherits a base class, an object of the derived class may be referred to (or cast) as either being the base class type or the derived class type. If there are base class methods overridden by the derived class, the method call behaviour is ambiguous.

The distinction between virtual and non-virtual resolves this ambiguity. If the function in question is designated "virtual" in the base class then the derived class's function would be called (if it exists). If it is not virtual, the base class's function would be called.

Virtual functions overcome the problems with the type-field solution by allowing the programmer to declare functions in a base class that can be redefined in each derived class.

Programming language supports for virtual function:

C++: virtual methods are declared by using the virtual keyword followed by the function name and the parenthesis ().

Java: In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual. To override a method, use an annotation '@Override' (could be omitted) followed by function definition.

Python: In Python all class functions (methods) are virtual. And no special keywords needed to make overriding or virtualization happen. It just works automatically!

Reference: wiki

07 December 2010

Deep copy vs. Shallow copy vs. Lazy copy

There are basically three strategies for copying objects; each has its own advantages and disadvantages.

Shallow Copy

Shallow copy is basically passing references, not actually copying data inside objects. That is why shallow copy is otherwise known as address copy. The main advantage of shallow copy is it is very fast and does not depend on the size of data; however, if the language does not support automatic garbage collection, a shallow copy could lead to a memory leak if not cautious enough. In addition, two object references refer to the same data block on memory after shallow copy.

Deep Copy 

This is the opposite of shallow copy. The data from one object is actually copy over to another object. Therefore, two object bare the same data after deep copy and yet there are still different objects! The disadvantage of this strategy is it is slow and expensive; however, deep-copied objects do not depend on each other and are independently modifiable.

Lazy Copy

A lazy copy is a combination of both strategies above. When initially copying an object, a shallow copy is used. A counter is also used to track how many objects share the data. When the program wants to modify an object, it can determine if the data is shared and can do a deep copy if necessary. This is also very similar to 'copy-on-write' technique used in most OSes.

So, how are copy actually implemented in programming languages?

In Java:  

Using clone method of a class.

In Python: 

the library's copy module provides shallow copy and deep copy of objects through the copy() and deepcopy() functions, respectively. Programmers may define special methods __copy__() and __deepcopy__() in an object to provide custom copying implementation.

16 November 2010

Python inheritance examples

Here are a few links that provide examples for Python inheritance:

http://www.wellho.net/solutions/python-inheritance.html
http://tinyurl.com/q9ambl

The only thing to note is to use super() with caution.

Python toString() class method?

Again, this is a common question regarding to Python OOP. In Java, we often overwrite a class method toString() for our own class, is there an equivalent thing in Python?

The answer is ... YES!

Just by redefining an special "__str__(self):" method in your own class, you can have your own human-readable string representation of your class object! What a beauty!

25 October 2010

Python class attributes v.s. data attributes

In Java, both static variables (called class attributes in Python) and instance variables (called data attributes in Python) are defined immediately after the class definition (one with the static keyword, one without). In Python, only class attributes can be defined here; data attributes are defined in the __init__ method.

Class attributes can be used as class-level constants, but they are not really constants.

Python supports data attributes (called “instance variables” in Java and “member variables” in C++). Data attributes are pieces of data held by a specific instance of a class. To reference this attribute from code outside the class, you qualify it with the instance name, instance.data, in the same way that you qualify a function with its module name. To reference a data attribute from within the class, you use self as the qualifier. By convention, all data attributes are initialized to reasonable values in the __init__ method. However, this is not required, since data attributes, like local variables, spring into existence when they are first assigned a value.

22 October 2010

Python singleton design pattern

How to define a class with a singleton instance? From http://python.org/dev/peps/pep-0318/, here is how:

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...


However, you can also achieve singleton without such clumsy code - use python module. See here:

http://tinyurl.com/yeotybq.

A module with functions and module scope variables is handy for such purpose! So no OOP is needed?! However, be cautious with singleton design pattern. Watch this blog post from google testing blog.

18 August 2010

Python __init__ and __new__

What is the difference between __init__ and __new__?

Each NEW-style python class has (or inherits from object class) a static method (can be called without creating an object) named __new__. When you call C(*args, **kwds) to create a new instance of class C, Python first calls C.__new__(C, *args, *kwds). Python uses __new__'s return value x as the newly created instance. Then Python calls C.__init__(x, *args, **kwds), but only when x is indeed an instance of C or any of its subclasses.

Thus, the statement x=C(23) is equivalent to:


x = C.__new__(C, 23)
if isinstance(x, C): type(x).__init__(x, 23)


So basically, __new__ is just like new keyword in Java; __new__ and __init__ combine together provide the functionality of an object constructor!

27 July 2010

Delegation Pattern

A nice explanation here: http://en.wikipedia.org/wiki/Delegation_pattern

The python code example on that web page even elaborates this design pattern in more details.