This is a read-only archive!

SCJP continued

Another SCJP study chapter down. I no longer feel bad about missing some questions in the last chapter, because THIS chapter is the one that talks about abstract classes being able to implement interfaces etc. Nice to ask questions about things before actually covering them.

Those silly default no-arg constructors in Java. I missed one review question about those. This is an example of the opposite of the "principle of least surprise" so touted in Perl and Ruby. Default constructors are magically automatically created in Java, but only if you don't supply any constructors of your own. Calls to superclass constructors are magically inserted in all constructors including those you define yourself, but they're always calls to super() with no arguments, and those super() calls aren't inserted into any constructor that calls another constructor as its first line. And so on and so forth.

Interesting that interfaces can extend multiple interfaces, while classes cannot extend multiple classes. One of the reasons behind forbidding multiple inheritance is supposedly so that you don't have to deal with method name collisions when multiple parent classes each let a child inherit methods with the same name. I tested what happens when there are name collisions in interfaces:

interface Blarg {
    public void test();
}

interface Blarg2 {
    public int test();
}

public class Test2 implements Blarg, Blarg2 {
    public void test() {}
    public static void main(String [] args) {}
}

It appears in this case there is no way to actually implement both the Blarg and Blarg2 interfaces in one class. (If there is, I can't see it.) You can't have two methods with the same name, same argument signature, and different return value. Trying to compile this fails with a "Hey you forgot to implement Blarg2's test() method" error. Similarly if I try

interface Blarg3 extends Blarg, Blarg2 {}

I get an error about Blarg and Blarg2 being "incompatible" because both define a method of the same name. That's handy. (Why not use the same error and allow multiple inheritance, and forbid it only whenever there are method name collisions? Who knows. Not I. I'm sure there are reasons. I hope there are reasons.)

I have a very good grasp on overriding vs. overloading. I remember going over it in my very first C++ class at college. I've somehow carried it all the way with me. Same goes with typecasting. Perl/Ruby don't have an equivalent, but I remember enough of it from C++. I also don't seem to have any trouble remembering which things happen at runtime and which things happen at compile-time. That should serve me well on the exam.

January 16, 2007 @ 3:53 PM PST
Cateogory: Programming
Tags: College, SCJP, Java