December 24, 2009

Inner classes

Inner classes are the same as nested classes
Method-local inner classes
Anonymous inner classes
Static inner classes (which are the same as static nested classes) are not like "regular" inner/nested classes; they're regular classes which are static members of their containing classes, similar to a static String or static int.

FINISH THIS

Overriding vs. Overloading vs. Hiding

  • Overloading is using the same method name with a different parameter list.
  • Overriding is replacing a superclass method with a different and/or more specific one in a subclass.
  • Hiding is similar to overriding but not quite the same. In the special case where a subclass's static method has the same signature as a parent class's static method, the subclass's method hides rather than overrides the parent class's method. This makes the parent class's method completely unaccessible. TODO: Find out whether this is the only situation in which hiding applies.

Useful links
The best explanation I've found so far, from the JavaRanch FAQ

Also useful, from the Java Tutorials

This StackOverflow post is technically about .NET, but I think it's still correct for Java

Some examples from the Java Language Specification

December 22, 2009

Parameterizing Wicket tables

Constructors for DefaultDataTables — including AjaxFallbackDefaultDataTables — include one or the other of:


IColumn<T>[] columns
java.util.List<IColumn<T>> columns


In other words, the parameter of the table — T — should be the same as the parameter of its columns.

Wicket ChoiceRenderers should take the same parameter as their DropDownChoices

From the Wicket 1.4.1 API:


new DropDownChoice("users", new Model(selectedUser), listOfUsers, new ChoiceRenderer("name", "id"));

Java generics, name clash and erasure

In progress: Adding to this post

General Overview

http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

FILL IN fancy term

It is not legal to use List<SubtypeOfFoo> as a subtype of List<Foo>. This is counterintuitive, especially because it IS legal to treat SubtypeOfFoo[] as a subtype of Foo[]. (Aside: new Integer[] { 1, 2, 3 } instanceof Number[] returns true.) This makes sense, because it prevents the following error from occurring:

// Bicycle and Train are subclasses of Vehicle
public void foo() {
List<Bicycle> bikes = new ArrayList<Bicycle>
addVehicle(bikes);
}

public void addVehicle(List<Vehicle> vehicles) {
vehicles[0] = new Train();
}



The matching code using arrays, shown below, compiles okay but will throw an ArrayStoreException at runtime. This works for arrays but not for generified collections because type erasure (see next section) makes it impossible for the JVM to throw a generified-collection equivalent of the ArrayStoreException.


// Bicycle and Train are subclasses of Vehicle
public void foo() {
Biycle[] bikes = { new Bicycle(), new Bicycle(), new Bicycle() };
addVehicle(bikes);
}

public void addVehicle(Vehicle[] vehicles) {
vehicles[0] = new Train(); // Compiles, but will explode at runtime
}


ADD MORE INFO HERE

Type Erasure

This is basically a fancy term for "all information about generics goes away before runtime." To give slightly more detail, a modern compiler will check generics for correctness to the best of its ability and insert casts where needed. As soon as that's done, it discards — or, erases — the generics and finishes compilation. By runtime, the JVM has no idea that generics were ever used; the code looks the same as it would have before J2SE 5, when generics were introduced.

The name clash error

Remember parameters for parent classes! From http://elliottback.com/wp/name-clash-the-method-blah-has-the-same-erasure-as-type-blah-but-does-not-override-it/:

Name clash: The method [foo] of type [some generic type] has the same erasure as [foo again] of type [some other generic type] but does not override it

In some cases, this can be fixed by adding parameters to the superclass name in the class containing foo. That is, change

class Bar<T> extends SuperBar

to

class Bar<T> extends SuperBar<T>

Exceptions in Java

Exceptions in Java - flesh out this post

http://java.sun.com/docs/books/tutorial/essential/exceptions/advantages.html
http://www.artima.com/intv/handcuffs.html

Equality in Java

One of the few methods that comes with all Java classes is equals(). By convention, it tests for MEANINGFUL equality. Therefore, this code


Integer i1 = new Integer(5);
Integer i2 = new Integer(5);

boolean test1 = i1.equals(i2);
boolean test2 = i2.equals(i1);


should produce true for both calls.

On the other hand, the equality operator (==) tests to see whether two references actually point at the same object. It "simply looks at the bits in the variable, and they're either identical or they're not" -K. Sierra & B. Bates, SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065). So, the values in the previous example would be false, but this code:


Integer i1 = new Integer(5);
Integer i2 = i1;

boolean test = i1 == i2;


will produce true.

Finding memory leaks in Java

There's a popular misconception that Java is immune to memory leaks. That's actually true for C/C++-style memory leaks; the JVM's garbage collector makes it impossible for mere coders to forget a free(). However, as Satish Gupta and Rajeev Palanki of IBM describe, problems can arise when objects that are no longer needed are still referenced by living objects. For example, a programmer might typo a loop and only dereference n-1 of a Collection's elements at a time in a class with numerous instances.

One last-resort trick I learned — on a job interview, actually — for finding memory leaks is to override finalize(). Sure, it's impossible to predict when the method will run, but a few lines of debug info printed to the console twelve percent of the time is better than nothing printed all of the time, especially when you feel like you've already tried everything else.

December 17, 2009

Quick-reference table of Java access modifiers

The table on this page lists the differences between public, protected, package-protected — AKA no modifier — and private fields in Java:

ModifierClassPackageSubclassWorld
publicYYYY
protectedYYYN
[no modifier]YYNN
privateYNNN


Source: http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

Terms for easy searching later:
package-private, package-protected, access control, public, protected, private

December 16, 2009

CSS text alignment quirk

NOT OKAY:
<span style="text-align: center">
WORKS FINE:
<div style="text-align: center">

This is because span is an inline element but div is a block-level element. The text will technically be centered inside the span, but that's meaningless because the span will wrap itself tightly around its contents and will itself be placed where page flow dictates. Generally, a div will have the same width as its container, resulting in the desired effect.

Glossary

Eventually, this should probably be expanded to a list of links to glossary sub-pages based on first letter.

cohesion - "the degree to which a class has a single-well-focused purpose" -K. Sierra & B. Bates, SCJP Sun Certified Programmer for Java 6 Study Guide (Exam 310-065)

covariance - Child[] is a subtype of Parent[] (as long as Child is a subtype of Parent). FILL IN MORE cf. contravariance, invariance Wikipedia article

contravariance - FILL IN cf. covariance, invariance Wikipedia article

invariance - List<Child> is not a subtype or a supertype of — or in any way related to, really — List<Parent> FILL IN MORE cf. covariance, contravariance Wikipedia article

non-reifiable - "[a type] whose runtime representation contains less information than its compile-time representation" -J. Bloch, Effective Java, Second Edition (all parameterized types except unbounded wildcards) FILL IN MORE

ordered - FILL IN cf. sorted

sorted - FILL IN cf. ordered

type safety - a guarantee that objects of a given type can't be treated as objects of another type, with exceptions for subclasses; Stack Overflow definition

Permanent Generation

permgen (Permanent Generation, cf. Tenured Generation)
constant string pool
does stuff in string pool get overwritten/deleted/garbage collected ever?

List of special topics

strictfp keyword
Var-args
finalize() method
Assertions
Labeled break/labeled continue
Constant pools

Assertions in Java

Turn on assertions with the -ea or -enableassertions command line flag

In Eclipse, right-click on the file to run in Package Explorer, hover on "Run As" (or "Debug As") and select "Run Configurations..." (or "Debug Configurations..."). Then, select the "Arguments" tab and add the flag in the "VM arguments" box.

Discussion of assertions in production code from Dr. Dobbs