Saturday, March 6, 2010

Java Inheritance

  • Variables

    Kinds of variables base on scope: local, instance, class

    Hiding/Shadowing Variables
    - redeclaring a variable that’s already been declared somewhere else. The closest scope is used when you refer it through simple name.

    1) local var hides instance var
    - use this to access the instance var

    2) instance var hides inherited var
    - use super.name or cast the object to its super class, with the syntax ((Superclass)object).name
    - when the variable is accessed thru the object containing it, the variable used depends on the type the object it was declared with or casted to, not the runtime type of the object.

  • Methods

    Overloading
    - same name, diff arguments, return type doesn't matter

    Overriding
    - same signature (method name + arguments), same return type diff classes
    - instance to instance method only

    Hiding
    - static to static only
    - when the method is called thru the object containing it, the method used depends on the type the object it was declared with or casted to, not the runtime type of the object.

    Not allowed in methods but allowed in variables/fields:
    - static to non-static or vice versa
    - narrowing visibility
    - different return type (but same signature/name) -> compile error in methods

  • Object
    - implicit superclass of all classes
    - must be overridden in objects -> equals(), hashCode(), toString()

    clone() method
    -protected|public Object clone() throws CloneNotSupportedException
    aCloneableObject.clone();
    - aCloneableObject must implemenet Cloneable interface
    - default behavior of Object's clone() -> creates an object of the same class as the original object and initializes the new object's member variables. But if a member variable is an external object, say ObjExternal, ObjExternal is not cloned but shared. A change in ObjExternal made by one object will be visible in its clone also.

    equals() method
    - uses ==
    - if overridden, u must override hashCode() too. If two objects are equal, their hash code must also be equal.
    public boolean equals(Object obj) {
       if (obj instanceof Book)
           return ISBN.equals((Book)obj.getISBN());
       else
           return false;
    }
  • Abstract vs Interface
    - http://mindprod.com/jgloss/interfacevsabstract.html
    - when to use one over the other:
    General rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class.

No comments:

Post a Comment