If i have this code:
public class MySuperClass {
public String superString = "hello";
public MyChildClass makeChild() {
return new MyChildClass();
}
public class MyChildClass {
public String childString = "hi";
}
}
How can i get the MySuperClass instance from the MyChildClass instance?
Because i have this error:
There are VERY similar questions around stackoverflow, but this isn't a duplicate of any of them.
What is the mistake in my code? How can i achieve what i said above, without making a method in the nested class which returns MySuperClass.this ? Imagine i do not own the code of MySuperClass...
I think this can be done because in the MyChildClass i can access the super instance with MySuperClass.this, how can i get the MySuperClass instance attached to the child, from outside of the child class?
EDIT: i know casting is not the way to achieve this, it was an attempt to achieve what i wanted
You're mixing terms. "Child class" is pretty much always used for this relationship:
public class Parent {}
public class Child extends Parent {}
(And 'Parent' here, is termed the 'superclass' of Child).
In that context, 'how can I get my superclass from my child class' makes no sense. Child is an extension of Parent, when you write new Child() there is just one instance, and that one instance is a combination of the stuff in Child and in Parent. It's not 2 separate things.
What you're talking about are inner classes. This relationship:
public class Outer {
public class Inner {}
}
Inner/Outer, vs. Child/Parent or Sub/Super.
So, what you actually ask is: How do I get the outer class instance?
That is not possible. It is an implementation detail of Inner, and it is up to Inner to expose this. If it doesn't want to, you don't get to access it.
But there are hacks and workarounds.
Option #1: The code in Inner itself can do it
Within the {} that go with class Inner {} you can do it:
class Outer {
class Inner {
public Outer getOuterInstance() {
return Outer.this;
}
}
}
Option #2: Hack it
At the class/JVM level, inner/outer classes don't exist. They're all just classes. That's why, if you compile the above, you end up with 2 class files, not one: Outer.class as well as Outer$Inner.class. The outer instance that Inner has is represented by a field.
This field is generally called this$0, and is package private. So, something like:
Field f = Inner.class.getDeclaredField("this$0");
f.setAccessible(true);
Outer outer = (Outer) f.get(instanceOfInner);
But, in case the reflection code didn't already spell this out for you: Don't. This is horrible idea. A SecurityManager can stop you. The code is hard to read, this$0 doesn't make sense unless you riddle this with comments explaining what you're doing. Most of all, like any reflection, this is flat out not something the author of Outer/Inner intended for you to do, and whatever you use Outer for may simply not 'work' properly in some minor point release down the road, because you're not using this library in its intended fashion, therefore any support offered for it is lost. You pave your own road, which is bad, because you have no idea what the author truly intended, and you now effectively have to say that your libraries must never be updated without extensive testing, and not updating is a great formula to get yourself hacked. It's a bad idea in so many ways.
Also, the significantly reduced care for backwards compatibility as expressed by the current OpenJDK team (see project jigsaw which was the most breaking release of java in a good long while, how OpenJDK team almost decided to get rid of the SecurityManager within a single version jump until called back by the community, aggressive expansion of mostly pointless 'opens' checks, and more) - means that if you rely on this, don't be surprised if java18 or what not breaks your ability to do this, permanently.
So, do NOT do this.
Caveat: non-static inner classes bad.
The idea that the inner class actually has an invisible field of type outer is annoying and surprising. It stops garbage collection. It confuses your average java programmer because 'using' this java feature the way it was intended is very rare.
I therefore strongly suggest you always make your inner classes static, and if you really want an instance of Outer, make it explicit: Make Inner static, then give it a private final Outer outer; field.
It's equally efficient, it's very slightly more typing, but it is a lot more readable.
I'm stuck with a rather peculiar design problem. I'm using a Java ORM, and have defined one of my model classes as follows:
class User extends Model {
// . . .
}
Now, there are more models, and I'd like them all to support data validations. The idea is simple: As each setter method is called, an internal ArrayList of errors keeps getting populated.
Now, the mechanism of error handling is exactly the same for all the model classes. I can envision the following interface:
public interface ErrorReportable {
ArrayList<String> errors = new ArrayList<String>();
boolean hasErrors();
ArrayList<String> getErrors();
void resetErrors();
}
Now I have a problem: All the methods are abstract, which means I'll have to provide an implementation for all of them in my classes. This is sad, because all these methods are going to be implemented in exactly the same way. Ideally, this would've been another class I would've neatly inherited from, but sadly, there's no multiple inheritance in Java.
My next option is use default methods in interfaces, but here the problem is the errors field, which will become static whereas I need a regular field for each instance.
It looks like the only solution is composition, but then I'll have to have a hasErrors() method on User, which will go return this.error_obj.hasErrors(). This is fine, but not really neat in my opinion as I'm having to write things twice.
How can I do better?
I think it would be better for the model classes to only expose List<Error> validate() method, and to have a stand-alone validator that validates all the fields and collects the errors.
That way, the collected messages are not part of the model's state, you have explicit control over when will the validation happen, you're preferring composition (which is almost always a good thing), and the only method you need to implement in model class is the entity-specific validation.
If you ever need to add any cross-field validations, it will also be probably quite easy to extend this design to also perform those alongside with field validations.
If I get your need right, I would implement an own Model-class, that implements all neceaasary Interfaces and extends the Model-ancestor, but still is Abstract.
Then all your normal model-classes inherit from your abstract model-class to get the implementation for the interface and also the inheritance from the model-class (2nd Generation would that be). Any framework checking with 'instance of' will still check true for the later model-class.
The abstract class does not even have to have any abstract methods/members, but it should stay abstract to prevent direct instanciating from that class.
public abstract class myModel extends Model implements ErrorReportable{ ... }
public class User extends myModel { ... }
I'm wondering if there's any "clean" way to implement an optional variable throughout a class hierarchy without simply leaving it null and nullchecking all the time. Let's say I have the following abstract parent class:
public abstract class Item {
public String name;
public Item(String name){
this.name = name;
}
public String getName(){
return name;
}
Pretty straightforward. Now I have another abstract class that extends this and a couple more that extend that one, each with a few additional variables/methods of their own. Item also has a stub class extending it (nothing but a constructor that calls super()) that may not be necessary if Item can be made concrete, but that depends on the solution.
Now, let's say that any of these concrete classes could potentially contain an instance of MyObject. A large number of Items will be created. Some of the instances of any of the classes in the Item hierarchy will have it and some won't. There's no way for the program to tell at compile time. I can't really split the hierarchy into two separate but nearly-identical trees, one with MyObject and one without. That's going to lead to a lot of code duplication. Subclassing the concrete implementations with another concrete class containing MyObject would mean excessive typechecking, which would get ugly, especially if the hierarchy grows. Putting an interface/abstract class further up isn't an option either as that would put MyObject in everything. Regardless of the solution, all of these must have a common interface/abstract class.
I may be nitpicking and should just implement MyObject at the top of the hierarchy and nullcheck it or use a simple boolean method to tell me if it's present or not, but it still feels a bit sloppy to me and I'd like to find a better solution if possible.
Your description of problem reminds me the very motivation for the Decorator pattern - an overgrown class hierarchy with some kind of wanted "multiple inheritance" and "combination of super-classes". Have a look at the description of Decorator on internet, and for good example have a look at how the Reader / Writer standard Java classes are implemented.
In some places where a class hierarchy is present and the top most base class is an abstract class there is a static getInstance() method in the abstract class. This will be responsible for creating the correct sub-class and returning it to the caller. For example consider the below code.
public class abstract Product {
public static Product getInstance(String aCode) {
if ("a".equals(aCode) {
return new ProductA();
}
return ProductDefault();
}
// product behaviour methods
}
public class ProductA extends Product {}
public class ProductDefault extends Product {}
In Java, java.util.Calendar.getInstance() is one place this pattern has been followed. However this means each time a new subclass is introduced one has to modify the base class. i.e: Product class has to be modified in the above example. This seems to violate the ocp principle. Also the base class is aware about the sub class details which is again questionable.
My question is...
is the above pattern an anti-pattern ?
what are the draw-backs of using the above pattern ?
what alternatives can be followed instead ?
The interface is not an anti-pattern. But the way you've implemented it is rather poor ... for the reason you identified. A better idea would be to have some mechanism for registering factory objects for each code:
The Java class libraries do this kind of thing using SPIs and code that looks reflectively for "provider" classes to be dynamically loaded.
A simpler approach is to have a "registry" object, and populate it using dependency injection, or static initializers in the factory object classes, or a startup method that reads class names from a properties file, etcetera.
No it's not. It's more like factory method pattern http://en.wikipedia.org/wiki/Factory_method_pattern. E.g. Calendar.getInstance();. JDK is full of such examples. Also reminds of Effective Java Item 1: Consider static factory methods instead of constructors
There are a number of separate issues here.
getInstance is probably going to be a bad name. You explicitly want a new object you can play around with. "Create", "make", "new" or just leave that word out. "Instance" is also a pretty vacuous word in this context. If there is sufficient context from the class name leave it out, otherwise say what it is even if that is just a type name. If the method returns an immutable object, of is the convention (valueOf in olden times).
Putting it in an abstract base class (or in an interface if that were possible) is, as identified, not the best idea. In some cases an enumeration of all possible subtypes is appropriate - an enum obviously and really not that bad if you are going to use visitors anyway. Better to put it in a new file.
Anything to do with mutable statics is wrong. Whether it is reusing the same mutable instance, registration or doing something disgusting with the current thread. Don't do it or depend (direct or indirectly) on anything that does.
Based on the feedback i introduced a new ProductFactory class that took care of creating the correct Product. In my case the creation of the correct product instance depends on an external context (i've put the product code for the purpose of simplicity.. in the actual case it might be based on several parameters.. these could change over time). So having a Product.getInstance() method is not that suited because of the reasons outlined in the question. Also having a different ProductFactory means in the future.. Product class can become an interface if required. It just gives more extensibility.
I think when the creation of the object doesn't depend on an external context.. like in the case of Calendar.getInstance() it's perfectly ok to have such a method. In these situations the logic of finding the correct instance is internal to that particular module/class and doesn't depend on any externally provided information..
I understand that neither a abstract class nor an interface can contain a method that is both abstract and static because of ambiguity problems, but is there a workaround?
I want to have either an abstract class or an interface that mandates the inclusion of a static method in all of the classes that extend/implement this class/interface. Is there a way to do this in Java? If not, this may be my final straw with Java...
EDIT 1: The context of this problem is that I have a bunch of classes, call them Stick, Ball, and Toy for now, that have a bunch of entries in a database. I want to create a superclass/interface called Fetchable that requires a static method getFetchables() in each of the classes below it. The reason the methods in Stick, Ball, and Toy have to be static is because they will be talking to a database to retrieve all of the entries in the database for each class.
EDIT 2: To those who say you cannot do this in any language, that is not true. You can certainly do this in Ruby where class methods are inherited. This is not a case of someone not getting OO, this is a case of missing functionality in the Java language. You can try to argue that you should never need to inherit static (class) methods, but that is utterly wrong and I will ignore any answers that make such points.
You have a couple of options:
Use reflection to see if the method exists and then call it.
Create an annotation for the static method named something like #GetAllWidgetsMethod.
As others have said, try to not use a static method.
There are lots of answers about 'this does'nt make sense..' but indeed I met a similar problem just yesterday.
I wanted to use inheritance with my unit tests. I have an API and several its implementations. So I need only 1 set of unit tests for all implementations but with different setUp methods which are static.
Workaround: all tests are abstract classes, with some static fields with protected access modifier. In all implementations I added static methods which set these static fields. It works rather nice, and I avoided copy and paste.
I too am dealing with this problem. For those that insist that it "doesn't make sense", I would invite you to think outside of that semantic box for a moment. The program I am working with is inherently about reflection.
Reflection, as you know, can take three orders of magnitude longer than straight-up binary function calling. That is an inevitable problem, and the software needs to port to as many machines as possible, some of which will be 32 bit and slower than my development machine to begin with. Thus, the applicability of a class to the requested operation needs to be checked via a static method, and all of the reflective methods are run at once during module booting.
Everything works, first and foremost. I've built the entire thing. The only catch is that a module can be compiled in a .class without compile time checking to see if the identifying static function exists at all, resulting in an innately useless class. Without the identifier, and its included information, for security's sake the module is not loaded.
I clearly understand the issue with the complete definition of "abstract" and "static", and understand that they don't make sense together. However, the ability to have a class method that is compiler-enforced for inclusion is lacking in Java, and as much as I like the language, I miss it. Thus, this is a human constraint on every programmer that ever works on the software, which I'm sure we can all agree is a pain.
There's a lot of 'this makes no sense' or 'this can't be because' and 'why do you want it?' (or worse: 'you don't have to want it!') in all those answers. However, these answers also indirectly give reasons why it should be possible.
It must be differentiated between the concept and the implementation.
Sure, overriding a static method makes no sense. And it also isn't what the question was about.
It was asked for a way to force implementation of a certain static method (or constant or whatever) in every derived class of an abstract class. Why this is required it the matter of the one who wants to write an appllication with Jave, and no business of anyone else.
This has nothing to do with how the compiler compiles the method and how it is done at runtime.
Why shoudl it be possible? because there are things that are class specific (and not instance specific) and therefore should be static, while they NEED to be impleented in every single subclass (or class that implements an interface).
Let's say there is an abstract class 'Being'. Now there are subclasses like 'animals' and 'plants'.
Now there are only mammals and fishes allowed for animals. This information is specific to the animals class, not to any instance nor doe sit belong to any superclass or subclass. However, this information must be provided by teh class, not an instance, because it is required to properly construct an animal instance. So it MUST be there and it CANNOT be in the instance.
In fact, Java has such a thing- Every object has a class specific field 'class'. It is class-specific, not inherited, no override and it must be there. Well the compiler creates it implicitly, but obviously the compiler CAN do it. So why not allowing this for own fields too.
After all, it is just a matter of definition how the combination 'abstract static' is interpreted when the compiler checks the intheritance chain for abstract functions.
Nobody was ever demanding that there should be an inheritance of the superclass class functions (which could still make some sense, depending on what this function actually does - after all classes inherit static functions of their superclasses, even though you might get a warning that you should access it directly when you call it by the subclass))
But to summarize: the Java language offers no way to do it at compile time while there is no reason (othe rthan plain dogmatic) to not doing so.
The only way is to write a static final function to the abstract class that tries to find the static function/field of the subclass when it is loaded (or loads all existing subclasses and checks them). If properly made, it gives a runtime error on first use. Complex and dirty but better than nothing. At least it prevents bugs where you get the information from the wrong superclass.
It won't work for interfaces, though.
A type system allows you to express some constraints among types, but it's limited. That's why javadocs are littered with constraints in human language, asking people to follow rules that the compiler cannot check.
if you want to extend it beyond what language provides natively, you can write your own static analysis tool. that is not uncommon. for example: findbug. also IDEs do that too, they checking thing beyond what language dictates. you can write a plug in to enforce that a subclass must have a static method of such signature.
in your case, it's not worth it. have javadoc in the superclass urge implementors to include a static method, that's good enough.
I'll provide a convoluted way of expressing your constraint anyway, but DO NO DO IT. people get really carried away of make everything checkable at compile time, at the price of making code unreadable.
interface WidgetEnumerator
{
List getAllWidgets();
}
public class Abs<T extends WidgetEnumerator>
{
static List getAllWidgets(Class<? extends Abs> clazz){ ... }
}
public class Sub extends Abs<SubWidgetEnumerator>
{
}
public class SubWidgetEnumerator implements WidgetEnumerator
{
public List getAllWidgets() { ... }
}
How it works: for any subclass of Abs, it is forced to provide an implementation of WidgetEnumerator. subclass author cannot forget that. Now invocation Abs.getAllWidgets(Sub.class) contains sufficient information to resolve that implementation, i.e. SubWidgetEnumerator. It is done through reflection, but it is type safe, there are no string literals involved.
I think I can give you a better answer after seeing your edits--your best bet is probably a factory pattern. (Not lovely, but better than singleton).
abstract class Widget
public static Widget[] getAllWidgetsOfType(Class widgetType) {
if(widgetType instanceof ...)
}
class Ball extends Widget
class Stick extends Widget
class Toy extends Widget
This is not a very good way to do it, but it's typical. Hibernate is the tool you would normally use to solve this problem, this is exactly what it's designed for.
The big problem is that it requires editing the base class whenever you add a new class of a given type. This can't be gotten around without reflection. If you want to use reflection, then you can implement it this way (Psuedocode, I'm not going to look up the exact syntax for the reflection, but it's not much more complex than this):
public static Widget[] getAllWidgetsOfType(Class widgetType) {
Method staticMethod=widgetType.getStaticMethod("getAllInstances");
return staticMethod.invoke();
}
This would give the solution you were asking for (to be bothered by the need to modify the base class each time you add a child class is a good instinct).
You could also make it an instance method instead of a static. It's not necessary, but you could then prototype the method (abstract) in Widget.
Again, all this is unnecessary and sloppy compared to Hibernate...
Edit: If you passed in a live "Empty" instance of a ball, stick or toy instead of it's "Class" object, you could then just call an inherited method and not use reflection at all. This would also work but you have to expand the definition of a Widget to include an "Empty" instance used as a key.
Static methods are relevant to an entire class of object, not the individual instances. Allowing a static method to be overridden breaks this dictum.
The first thing I would consider is to access your database from a non-static context. This is actually the norm for Java apps.
If you absolutely must use a static method, then have it parameterised with instance specific arguments (of a generic type) to allow the different subclasses to interact with it. Then call that single static method from you polymorphic methods.
No. You can't do that. If you're willing to compromise and make the method non-static or provide an implementation of the static method in your abstract class, you'll be able to code this in Java.
Is there a way to do this in Java?
I don't think there is a way to do this in any language. There's no point to it, since static methods belong to a class and can't be called polymorphically. And enabling polymorphic calls is the only reason for interfaces and abstract classes to exist.
Create a context interface containing your method with a name that matches your problem domain. (Name it "World" if you absolutely have to, but most of the time there's a better name)
Pass around implementation instances of the context object.
Ok, maybe my question was poorly asked, it seems like most of you didn't get what I was trying to do. Nonetheless, I have a solution that is somewhat satisfactory.
In the abstract super class, I am going to have a static method getAllWidgets(Class type). In it I'll check the class you passed it and do the correct fetching based on that. Generally I like to avoid passing around classes and using switches on stuff like this, but I'll make an exception here.
static methods can't be abstract because they aren't virtual. Therefore anywhere that calls them has to have the concrete type with the implementation. If you want to enforce that all implementations of an interface have a certain static method, then that suggests a unit test is required.
abstract class A
{
public static void foo()
{
java.lang.System.out.println("A::foo");
}
public void bar()
{
java.lang.System.out.println("A::bar");
}
}
class B extends A
{
public static void foo()
{
java.lang.System.out.println("B::foo");
}
public void bar()
{
java.lang.System.out.println("B::bar");
}
}
public class Main
{
public static void main(String[] args)
{
B b = new B();
b.foo();
b.bar();
A a = b;
a.foo();
a.bar();
}
}
For what it is worth I know exactly what you are trying to do.
I found this article while searching for the reasons I can't do it either.
In my case I have HUNDREDS of classes that inherit from a central base base and I want simply to get a reference like this:
ValueImSearchingFor visf = StaticClass.someArbitraryValue()
I do NOT want to write/maintain someArbitraryValue() for each and every one of hundreds of the inherited classes -- I just want to write logic once and have it calc a Unique Class-Sepcific value for each and every future written class WITHOUT touching the base class.
Yes I completely get OO - I've been writing Java for about as long as it's been available.
These specific classes are more like "Definitions" as opposed to actual Objects and I don't want to instantiate one every time I just need to see what someArbitraryValue() actually is.
Think of it as a PUBLIC STATIC FINAL that allows you to run a Method ONCE to set it initially. (Kinda like you can do when you define an Enum actually...)
I'd make a WidgetCollection class with an abstract Widget inner class.
You can extend the WidgetCollection.Widget class for each of your types of Widget.
No static methods necessary.
Example (not compiled or tested):
class WidgetCollection<W extends Widget> {
Set<W> widgets = new HashSet<W>();
Set<W> getAll() {
return widgets;
}
abstract class Widget {
Widget() {
widgets.add(this);
}
abstract String getName();
}
public static void main(String[] args) {
WidgetCollection<AWidget> aWidgets = new WidgetCollection<AWidget>();
a.new AWidget();
Set<AWidget> widgets = aWidgets.getAll();
}
}
class AWidget extends Widget {
String getName() {
return "AWidget";
}
}
It doesn't make sense to do what you're asking:
Why can't static methods be abstract in Java