I have been facing an odd phenomena that I don't quite understand. I have an abstract class that is extended by several other classes. the abstract class is a type of special collection and it has a nested abstract iterator class that fits it. Every class that extends the abstract collection class, also has a nester iterator class that extends the orginal abstract iterator.
The abstract class is something like this:
public abstract class AbstractMultiCollection<T> {
public AbstractMultiCollection() {
...
}
MultiIterator<T> iterator();
public abstract class AbstractMultiIterator {
public AbstractMultiIterator() {
...
}
The extending classes are something like this:
public class MajorityMultiCollection<T> extends AbstractMultiCollection<T> {
...
public MultiIterator<T> iterator() {
return new MajorityIterator();
}
...
public class MajorityIterator extends AbstractMultiIterator {
public MajorityIterator() {
super();
...
}
public T next() {
...
}
Simply put, the collections extend the abstract collection and their nested iterators extend the nested abstract iterator.
I have two problems that I don't understand and would appreciate clarification on:
When I debug my code, the "return new MajorityIterator();" lines raise a "Source Not Found" error and "ClassNotFound" exception in the eclipse debugger and a bunch of "ClassLoaderExt" exceptions that I don't understand.
I noticed that every "MajorityIterator" has two "This$0" fields, containing the collection he belongs to. one is null at first, but receives the collection once I invoke the "super();" builder.
I failed to find the reason for this, can anyone clarify? Thanks in advance!
Actually having two this references makes sense. One thing most people do not realize is how the Java compiler implements non-static nested classes:
It implicitly adds a new field with the type of the outer class, lets call it outer$object.
It implicitly adds a new argument for the outer class object to all constructors to fill in that field. Incidentally, that means that the default constructor of the inner class actually has a parameter, which makes using it via reflection significantly more complex.
It implicitly creates constructors and methods with wider visibility to get around any accessibility issues if e.g. the inner class is declared private.
Since the outer$object field needs to have the same type as the outer class, one will be added each time a nested class inherits from a class that is not nested within the same outer class.
Personally, I tend to avoid non-static non-anonymous inner classes, in order to keep everything explicitly on the surface, rather than let the compiler make a mess out of things...
A MajorityIterator object will indeed have two this$0 fields:
One (implicitly declared in MajorityIterator) for the reference to the enclosing instance of MajorityMultiCollection
One (implicitly declared in AbstractMultiIterator) for the reference to the enclosing instance of AbstractMultiCollection. This will be null until the super() call, as it'll be set in the constructor.
You might find it clearer to make these static nested classes, and explicitly pass in the reference to the enclosing instance instead - I suspect you only want one reference, and it'll be simpler to reason about.
Related
I have just found a static nested interface in our code-base.
class Foo {
public static interface Bar {
/* snip */
}
/* snip */
}
I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:
What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?
The static keyword in the above example is redundant (a nested interface is automatically "static") and can be removed with no effect on semantics; I would recommend it be removed. The same goes for "public" on interface methods and "public final" on interface fields - the modifiers are redundant and just add clutter to the source code.
Either way, the developer is simply declaring an interface named Foo.Bar. There is no further association with the enclosing class, except that code which cannot access Foo will not be able to access Foo.Bar either. (From source code - bytecode or reflection can access Foo.Bar even if Foo is package-private!)
It is acceptable style to create a nested interface this way if you expect it to be used only from the outer class, so that you do not create a new top-level name. For example:
public class Foo {
public interface Bar {
void callback();
}
public static void registerCallback(Bar bar) {...}
}
// ...elsewhere...
Foo.registerCallback(new Foo.Bar() {
public void callback() {...}
});
The question has been answered, but one good reason to use a nested interface is if its function is directly related to the class it is in. A good example of this is a Listener. If you had a class Foo and you wanted other classes to be able to listen for events on it, you could declare an interface named FooListener, which is ok, but it would probably be more clear to declare a nested interface and have those other classes implement Foo.Listener (a nested class Foo.Event isn't bad along with this).
Member interfaces are implicitly static. The static modifier in your example can be removed without changing the semantics of the code. See also the the Java Language Specification 8.5.1. Static Member Type Declarations
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with Foo.Bar, like so:
public class Baz implements Foo.Bar {
...
}
In most ways, this isn't different from a static inner class.
Jesse's answer is close, but I think that there is a better code to demonstrate why an inner interface may be useful. Look at the code below before you read on. Can you find why the inner interface is useful? The answer is that class DoSomethingAlready can be instantiated with any class that implements A and C; not just the concrete class Zoo. Of course, this can be achieved even if AC is not inner, but imagine concatenating longer names (not just A and C), and doing this for other combinations (say, A and B, C and B, etc.) and you easily see how things go out of control. Not to mention that people reviewing your source tree will be overwhelmed by interfaces that are meaningful only in one class.So to summarize, an inner interface enables the construction of custom types and improves their encapsulation.
class ConcreteA implements A {
:
}
class ConcreteB implements B {
:
}
class ConcreteC implements C {
:
}
class Zoo implements A, C {
:
}
class DoSomethingAlready {
interface AC extends A, C { }
private final AC ac;
DoSomethingAlready(AC ac) {
this.ac = ac;
}
}
To answer your question very directly, look at Map.Entry.
Map.Entry
also this may be useful
Static Nested Inerfaces blog Entry
Typically I see static inner classes. Static inner classes cannot reference the containing classes wherease non-static classes can. Unless you're running into some package collisions (there already is an interface called Bar in the same package as Foo) I think I'd make it it's own file. It could also be a design decision to enforce the logical connection between Foo and Bar. Perhaps the author intended Bar to only be used with Foo (though a static inner interface won't enforce this, just a logical connection)
If you will change class Foo into interface Foo the "public" keyword in the above example will be also redundant as well because
interface defined inside another interface will implicitly public
static.
In 1998, Philip Wadler suggested a difference between static interfaces and non-static interfaces.
So far as I can see, the only difference in making an
interface non-static is that it can now include non-static inner
classes; so the change would not render invalid any existing Java
programs.
For example, he proposed a solution to the Expression Problem, which is the mismatch between expression as "how much can your language express" on the one hand and expression as "the terms you are trying to represent in your language" on the other hand.
An example of the difference between static and non-static nested interfaces can be seen in his sample code:
// This code does NOT compile
class LangF<This extends LangF<This>> {
interface Visitor<R> {
public R forNum(int n);
}
interface Exp {
// since Exp is non-static, it can refer to the type bound to This
public <R> R visit(This.Visitor<R> v);
}
}
His suggestion never made it in Java 1.5.0. Hence, all other answers are correct: there is no difference to static and non-static nested interfaces.
In Java, the static interface/class allows the interface/class to be used like a top-level class, that is, it can be declared by other classes. So, you can do:
class Bob
{
void FuncA ()
{
Foo.Bar foobar;
}
}
Without the static, the above would fail to compile. The advantage to this is that you don't need a new source file just to declare the interface. It also visually associates the interface Bar to the class Foo since you have to write Foo.Bar and implies that the Foo class does something with instances of Foo.Bar.
A description of class types in Java.
Static means that any class part of the package(project) can acces it without using a pointer. This can be usefull or hindering depending on the situation.
The perfect example of the usefullnes of "static" methods is the Math class. All methods in Math are static. This means you don't have to go out of your way, make a new instance, declare variables and store them in even more variables, you can just enter your data and get a result.
Static isn't always that usefull. If you're doing case-comparison for instance, you might want to store data in several different ways. You can't create three static methods with identical signatures. You need 3 different instances, non-static, and then you can and compare, caus if it's static, the data won't change along with the input.
Static methods are good for one-time returns and quick calculations or easy obtained data.
What's the difference between using interface inside class, inside nested class and outside class.
As I was reading about the class DataStructure.java in Questions and Exercises: Nested Classes at Oracle (pasting here fragment of the example):
public class DataStructure {
//some code
interface DataStructureIterator extends java.util.Iterator<Integer> { }
// Inner class implements the DataStructureIterator interface,
// which extends the Iterator<Integer> interface
private class EvenIterator implements DataStructureIterator {
//rest code
So as the code about shows there is no any body in interface. Couldn't I just extends EvenIterator class with java.util.Iterator<Integer> instead of creating this interface and implements it?
Is there any other difference (aside from code readability) between declaring interference outside/inside class?
What will happen when the outer class gonna be extended by a interface. Will it impact in any way on nested class?
Just want to be sure about these things to know how to use them properly, thanks for your time.
So as the code about shows there is no any body in interface. Couldn't I just extends EvenIterator class with
java.util.Iterator instead of creating this interface and
implements it?
Yes, you could. But this way it may be more readable and extendable. Even if there are no members now, they may be added later.
Is there any other difference (aside from code readability) between declaring interference outside/inside class?
A nested interface is implicitly static, so the only effect is that a nested interface is a part of the enclosing class namespace-wise.
Because members of a class may be declared as protected or private, that applies to nested interfaces as well. It rarely makes sense to use private interfaces, though, because they can only be implemented in the same class, so why bother with interfaces in the first place? However, protected interfaces may be useful. For example, you may have an abstract factory method that is used by the subclasses to provide instances to the parent class. Here's a contrived example:
public abstract class Enclosing {
protected interface JobHandler {
void handle(Job job) throws JobException;
}
protected abstract JobHandler createJobHandler();
// public methods omitted
private void doTheJob(Job job) {
createJobHandler().handle(job);
}
}
If the interface is declared package-private, it might as well just be at the package level. The only reason you may want to cram it inside a class is because it's very tightly coupled to the class itself. Perhaps it's some sort of helper interface that is used strictly in unit testing that particular class.
If the interface is public, then it's usually a bad idea to make it nested. Because by doing that, you increase coupling between the interface and the enclosing class. And interfaces are one of the best ways to reduce coupling! So why waste their potential?
Suppose you have a mylib-buttons library that have a Button class. One day having a Button.ClickListener seems to be a nice idea. Then you want to reuse this interface in another class, and possibly even in another library. But you can't do it without introducing a (probably unnecessary) dependency on the library that contains the Button class. On the other hand, if it's a top-level interface, then you just extract the interfaces into another library, say, mylib-core, leaving the messy buttons alone in the mylib-buttons.
Nested interfaces inside interfaces is a bit different story. They can be a part of the same design and intended to be used together. #cricket_007 in one of the comments gives a good example of that: Map.Entry.
What will happen when the outer class gonna be extended by a interface. Will it impact in any way on nested class?
This is not exactly clear. How can a class be extended by an interface? Nevertheless, whatever you meant here, you can probably answer it yourself if you consider the aforementioned fact: the nested interface is just a part of the class' namespace scope, and that's it. There are no other impacts whatsoever.
I've read about class fromal parameters and the question then arises as to why the following code is ill-formed?
class A:
package org.gradle;
public class A extends B.Inner{
public A(B s){
s.super(new B()); //error
s.super(); //OK
}
}
class B:
package org.gradle;
public class B{
public class Inner{
}
}
The key part of what was said is:
The constructor of a non-private inner member class implicitly
declares, as the first formal parameter, a variable representing the
immediately enclosing instance of the class
So, I expect that besides the default constructor, we should have a constructor with the following signature:
Inner(B b);
Why not?
The "extra" parameter is effectively hidden from you - both when you declare it, and when you execute it. When you execute it, you provide a value in a different way - in your case, via s:
s.super();
That's passing s as the hidden extra argument to the B.Inner constructor. The syntax for all of this is a little weird - and I would personally try to avoid using inner classes in this sort of situation... they just get weird very quickly. I usually prefer static nested classes, and if I do need an inner class, it's almost always private. Subclassing an inner class declared in a different top-level class is an odd situation, IMO.
You are already passing the enclosing instance s (of class B) to the constructor of the inner class when you call s.super(), so there's no need to pass another instance of B.
The variable representing the immediately enclosing instance of the class is an implicit parameter, and it is passed to the constructor using a special syntax.
I'm trying to use extends (inheritance) in Java. I made a quick abstract class to extend from, and then extended it. However my IDE now is saying that "An enclosing instance that contains abstract_class is required" and gives my constructor for the derived classes big error lines. What on earth is it going on about? The abstract class doesn't have or need any sort of constructor.
Just for reference, I'm using extends rather than implements in part because the implementation details that I don't want to have to maintain for every derived class which are identical involve using reflection on this.
Edit: I've read some of the responses. What in God's name is a static (or non-static, for that matter) class? And just to irritate all of you, it didn't solve the problem.
// some_class.java
public class some_class {
public static abstract class abstract_class {
...
}
...
}
// Model.java
public class Model extends some_class.abstract_class {
public Model(...) {
// No enclosing instance! Critical error.
...
}
...
}
And I thought that C++'s header files were bad.
The code you posted seems to compile just fine for me. Try doing a clean build in your IDE and it should work.
Just for your own curiosity, Java has 2 types of inner classes: static and regular or (non-static). If you don't include the static keyword for an inner class definition, it means that an instance of that class will always require an instance of the parent class. For ex:
public class MyClassOuter {
//...
public class MyClassInner {
//..
}
}
If you write that, it is understood that any instance of MyClassInner will have an implicit reference to an instance of MyClassOuter.
Static, on the other, hand implies no such thing. It is just a class definition that happens to be inside another class definition. The outer class is used almost like a package (though not quite).
if you have
interface MyInterface
{
abstract class MyAbstractClass {
// ...
}
}
and then you try
class ConcreteClass extends MyAbstractClass {
}
You will get the error described. The fix is to either move MyAbstractClass to a top-level class (put it in it's own file - not strictly necessary for non-public classes, but keeps the code organized.) Alternatively, add the static modifier to the MyAbstractClass declaration.
The "enclosing instance" message almost certainly implies that you have a (non-static) inner class for your superclass. In most cases, inner classes can and should be static - that's likely the best workaround here. Alternatively, as the message says, you will need to use an enclosing instance of the "outer" class, if your parent really makes sense as a non-static inner class.
Posting some code will help disambiguate between these causes and suggest the best way to resolve it. I'll also be able to give examples of the resolutions with the right class names - currently I don't think arbitrary names will help that much as it sounds like you hadn't identified the inner/outer class issue.
You need to in your child class add in the constructor super() that super class can be created.
class A{
.
.
.
class B{
. . .
}
}
if you want to access the Class B and it it is not static inner class you can write the code as
A.B objOfB = new A(). new B();
I've got the following:
public abstract class Foo<T>{
//contents of Foo //
...
public class Bar<Q> extends Foo<T>{
//contents of Foo.Bar //
...
}
}
Later, in another class and java file, I am trying to construct an instance of the inner Bar class above, using the outer abstract class as a supertype. To complicate things even more, the new class has it's own generic. The following does not work:
public class SomeOtherClass<A>{
private Foo<A> x;
public SomeOtherClass(){
x = Foo<A>.Bar<A>();
}
}
But this doesn't work; and neither do all the other combos that I've tried. So how do I go about instantiating x? Can it be done with out removing Foo's parameter? I don't want to remove Foo's parameter, because it's abstract methods have the generic parameter in their signatures.
To get an instance of the inner class you first need an instance of the outer class. As Foo in your example is abstract you can't instantiate the outerclass. Thus you also can't instantiate the innerclass.
For your example you can use the dirty trick (as there are no abstract methods to implement)
public class SomeOtherClass<A>{
private Foo<A> x;
public SomeOtherClass() {
//create anonymous extension of the abstract outer class
//for a real abstract class this would mean you have to
//implement all methods which are declared abstract
x = new Foo<A>(){};
x = x.new Bar<A>();
}
}
So actually you should ask yourself if your class structure is right, if you need access to a innerclass (Bar) of an abstract class (Foo) without really needing the enclosing class.
Aside from inquiry for exploration's sake, what's the motive for nesting Bar within Foo? This looks almost like how enum and Enum work, but without the behind-the-scenes compiler magic to hide most of the oddities.
If Foo is incomplete, it's meant to be extended from afar -- even if only from no farther than within its containing package (if the class wasn't declared public). The extensions being nested within the incomplete husk will only confuse potential clients.
If you share more detail about the actual problem domain, you'll likely summon plenty of specific replies as to how to better model the solution.
Bar is a non-static inner class of Foo. That means that you need an instance of Foo to construct an instance of Bar. If you don't want to need an instance of Foo, then Bar should be made a static inner class.