Java: Return class (Not an instance)

Martijn Courteaux picture Martijn Courteaux · Dec 19, 2009 · Viewed 27.8k times · Source

Is it possible to return in a static method a class? I will explain...

I have:

public class A { public static void blah(){} }
public class B { }

I want to create a static method in B witch returns A. So you can do:

A.blah();

And

B.getA().blah();

This, without creating an instance of A. Just use it static methods.

Is this possible?

Answer

Stephen C picture Stephen C · Dec 20, 2009

This is a rebuttal of @irreputable's answer:

public class B { 
    public static A getA(){ return null; }
}

B.getA().blah(); //works!

It "works", but probably not in the sense that you expect, and certainly not in a useful way. Let's break this down into two parts:

A a = B.getA();
a.blah();

The first statement is returning a (null in this case) instance of A, and the second statement is ignoring that instance and calling A.blah(). So, these statements are actually equivalent to

B.getA();
A.blah();

or (given that getA() is side-effect free), just plain

A.blah();

And here's an example which illustrates this more clearly:

public class A {
   public static void blah() { System.err.println("I'm an A"); }
}

public class SubA extends A {
   public static void blah() { System.err.println("I'm a SubA"); }
}

public class B { 
   public static A getA(){ return new SubA(); }
}

B.getA().blah(); //prints "I'm an A".

... and this (I hope) illustrates why this approach doesn't solve the OP's problem.