Java: return class (not an instance)
•
Java
Can I return a class as a static method? I'll explain
I have:
public class A { public static void blah(){} } public class B { }
I want to create a static method in B witch to return A. so you can do:
A.blah();
and
B.getA().blah();
In this way, an instance of a is not created Just use its static method
Is that possible?
Solution
This is a rebuttal to @ the indisputable answer:
public class B { public static A getA(){ return null; } } B.getA().blah(); //works!
It "works", but it may not be in the sense you expect, and certainly not a useful way Let's divide it into two parts:
A a = B.getA(); a.blah();
The first statement returns an instance of a (null in this case), and the second statement ignores the instance and calls a. blah() So these statements are actually quite
B.getA(); A.blah();
Or (because geta () is a side effect), it's just simple
A.blah();
Here is an example to illustrate this:
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) explains why this approach does not solve the op problem
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码