Tuesday, May 18, 2010

SCJP Exam Watch 7 - Object Orientation (3)

Don't be fooled by a method that's overloaded but not overridden by a subclass. It's perfectly legal to do the following:

public class Foo {
    void doStuff() {}
}

class Bar extends Foo {
    void doStuff(String s) {}
}

The Bar class has two doStuff() methods: the no-arg version it inherits from Foo (and does not override), and the overloaded doStuff(String s) defined in the Bar class. Code with a refrence to a Foo can invoke only the no-arg version. but code with a reference to a Bar can invoke either of the overloaded versions.


Refrence: SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065)

SCJP Exam Watch 6 - Object Orientation (2)

Be careful to recognize when a method is overloaded rather than overridden. You might see a method that appears to be violating a rule for overriding, but that is actually a legal overload, as follows:

public class Foo {
    public void doStuff(int y, String s) {}
    public void moreThings(int x) {}
}

class Bar extends Foo {
    public void doStuff(int y, long s) throws IOException {}
}

It's tempting to see the IOException as the problem, because the overridden doStuff() method doesn't declare an exception, and IOException is checked by the compiler.

But the doStuff() method is not overridden! Subclass Bar overloads the doStuff() method, by varying the argument list, so the IOException is fine.


Refrence: SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065)

SCJP Exam Watch 5 - Object Orientation (1)

If a method is overridden but you use a polymorphic (supertype) reference to refer to the subtype object with the overriding method, the compiler assumes you're calling the supertype version of the method.

If the supertype version declares a checked exception, but the overriding subtype method does not, the compiler still thinks you are calling a method that declares an exception.

Let's take a look at an example:

class Animal {
    public void eat() throws Exception {
        // throws an Exception
    }
}

class Dog extends Animal {
    public void eat() {
        /*no Exceptions*/
    }

    public static void main(String[] args) {
        Animal a = new Dog();
        Dog d = new Dog();
        d.eat();        // OK
        a.eat();        // Compiler error - unreported exception
    }
}

This code will not compile because of the exception declared on the Animal eat() method. This happens even though, at runtime, the eat() method used would be the Dog version, which does not declare the exception.

Refrence: SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065)
Java, JavaScript, HTML, XHTML, AJAX, CSS, etc.