How to instantiate an inner class without instantiating the outer - java

I've been following this tutorial for creating a database and have one question. It says "To access your database, instantiate your subclass of SQLiteOpenHelper:
FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());". But how can I instantiate my FeedReaderDbHelper class in another class (in a service in my case) without instantiating the whole FeedReaderContract class, because it says I should avoid instantiating the former class? In my service I am doing this:
FeedReaderContract.FeedReaderDbHelper mDbHelper = new FeedReaderContract().new FeedReaderDbHelper(mContext);
But the tutorial says it's forbidden.

If your inner class is associated to an instance of your outer class, you wouldn't be able to do that. IOW, if your inner class is not a static inner class, then it really doesn't make sense to create your inner class alone, right?
On the other hand, you can change your inner class to a static inner class. But you have to be careful if this is what you need since you are basically saying that the static inner class is not dependent on any one instance of the outer class.
Check this out: https://stackoverflow.com/a/70358/2231632

Related

Singleton-pattern destroyable by inner class?

I wrote a class following the Singleton-pattern and would like to write a inner class for it next.
What worries me is that the inner class is able to access all of the outer classes private fields, including the private field for the single instance and i suppose the private constructor likewise.
Is it possible to attack the singleton and to make a second instance of it when one has access to the constructor of the inner class?
I was thinking of some kind of navigating from an instance of the inner class to the constructor of the class.
So for example:
class Outer{
private static Outer instance;
private Outer(){}
public static Outer getInstance(){
if(instance==null)instance= new Outer();
return instance;
}
class Inner{
public Inner(){}
}
and now something like:
public class Main{
public static void main(String[]args){
Outer outer = Outer.getInstance();
Inner inner = outer.new Inner();
Outer outer2 = inner.Outer.this.new Outer();
}
}
Noticing that the last line is not compilable I thought there might be some other way to "navigate" to the constructor of the outer class once one has an object of the inner class.
What worries me is that the inner class is able to access all of the
outer classes private fields, including the private field for the
single instance and i suppose the private constructor likewise.
That's the whole purpose in life of inner class, read more here, inner classes are meant for the situation when you want to keep some state of a class as private but still want a cohesive class to access it, so in those situation you make an inner class for that top level class.
Is it possible to attack the singleton and to make a second instance
of it when one has access to the constructor of the inner class?
If you have implemented proper singleton pattern for your top level class then no-one can create another instance of your top level class.
Also, just in case if you are thinking otherwise then when you create an instance of inner class then it doesn't create an instance of outer class, no there again there are scenarios like if you have a static inner class then you do need an instance of top level class but if you have a non-static inner class then first you need to create a instance of top level class and then you create instance of your inner class, but whole point is that creating an instance of inner class doesn't create another instance of outer class, so if you have implemented singleton pattern properly in our outer class then you are fine.
I would recommend you to read about inner classes here.
Singleton-pattern destroyable by inner class?
With above explanation, answer is no, with a properly implemented singleton pattern in top level class, an inner of it cannot create another instance of the top level class.
Your question seems to indicate that you're trying to prevent an attacker from making specific changes in your source code. If someone has that level of access already, there's no security on Earth that can protect you from an attack.

Static nested class instance [duplicate]

This question already has answers here:
Java inner class and static nested class
(28 answers)
Closed 7 years ago.
I came across this in java, I know its a static nested class but why create an instance of 'static'. Isn't the whole idea of 'static' to use it without an instance? I understand the concept of inner classes, but why (and frankly how is it possible to) create an 'instance' of a 'static' member at all ?
Why this:
1- OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
2- nestedObject.aNestedClassMethod();
and not this:
1- OuterClass outerInstance=new OuterClass();
2- outerInstance.StaticNestedClass.aNestedClassMethod();
Use on inner classes, the keyword static indicates that you can access the inner class without an instance of the outer class.
For example:
public class Outer {
public static class Inner {
/* Code here. */
}
}
with this construction, you can create an instance of the inner class by using this code:
new Outer.Inner()
If the inner class would not be static, but also like this:
public class Outer {
public class Inner {
/* Code here. */
}
}
Then, you would have to create an instance of Outer in order to access Inner:
new Outer().new Inner()
Don't think of a static class as being a member of its enclosing class. It's a class of its own, totally separate. The only real distinction between it and a top-level class is that it has a slightly different name, and it can be private — which again doesn't affect its semantics, other than the fact that only the enclosing class knows about it.
So, if I have:
public class EnclosingClass {
public static class InnerClass {
}
}
Then anyone can come around and do:
EnclosingClass.InnerClass instance = new EnclosingClass.InnerClass();
See: exactly the same as a top-level class.
This is actually true of an inner class, too. There things are slightly more complicated, but basically the idea is that the inner class is still its own class, but it has a (mostly hidden) reference to the instance of the enclosing class that created it. I say "mostly" because it's possible to access that instance, via EnclosingClass.this. The java compiler also does some convenience plumbing for you, such that someFieldInTheEnclosingClass becomes EnclosingClass.this.someFieldInTheEnclosingClass. But don't let that shorthand fool you: the inner class is its own separate class, and its instance is its own separate instance; they're no different than a top-level class in that regard.
Thanks everyone who replied and commented. I have finally got the hang of it. I guess the answer was right in front of my eyes.
The reason behind calling a an inner static class 'static' is how its referenced and not how the class behaves. Since we don't need and instance of the OuterClass to create an instance of InnerClass and we simply use OuterClass name, rather than its object to instantiate the inner class.
Special thanks to Sleiman Jneidi, who posted the very first comment, the name static here "is" misleading.
1- OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Can outer classes call methods of its inner class?

I have code establishing a server connection upon the event that a user clicks a specific button. I created an inner class to listen for the action. Within the single method I have in the inner class, I also establish that server connection mentioned earlier.
My question is, can the Socket connection only be utilized from within the "inner" class? Or, can the outer class proceed with communication with said server?
I do, however, understand that the inner class has unrestricted access to the outer class(as if it were the outer class. My question is the other way around.
Create an instance like this and access what you want:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
All methods declared on the inner class are accessible ... whether they are declared as public or ... private.
If the inner methods are static then they can always be called by code in the outer class. You just need to qualify the method name with the inner class name.
Otherwise, the outer class code needs a reference for an instance of the inner class to call methods on it. (But that's normal.)
(If you were asking about whether an inner class could call methods on the outer class, it is a bit more complicated. Most of the above applies, but if the inner class is NOT static it can also call instance methods on its outer class via this.)
Yes ,you can achieve this look below sample code
currentDateMinutes=getDateAndTime();
System.out.println("DATE & TIME:"+new JobSchedulerUtil().new TaskScheduler(currentDateMinutes).timeNow());
Above code JobSchedulerUtil class is an outer class with having getDateAndTime() method and an inner class TaskScheduler with timeNow() method.

Why does Android prefer static classes

I see a lot of java code where android prefers to have developers use static inner classes. Particularly for patterns like the ViewHolder Pattern in custom ListAdapters.
I'm not sure what the differences are between static and non-static classes. I've read about it but it doesn't seem to make sense when concerned with performance or memory-footprint.
It's not just Android developers...
A non-static inner class always keeps an implicit reference to the enclosing object. If you don't need that reference, all it does is cost memory. Consider this:
class Outer {
class NonStaticInner {}
static class StaticInner {}
public List<Object> foo(){
return Arrays.asList(
new NonStaticInner(),
new StaticInner());
}
}
When you compile it, what you get will be something like this:
class Outer {
Outer(){}
public List<Object> foo(){
return Arrays.asList(
new Outer$NonStaticInner(this),
new StaticInner());
}
}
class Outer$NonStaticInner {
private final Outer this$0;
Outer$NonStaticInner(Outer enclosing) { this$0 = enclosing; }
}
class Outer$StaticInner {
Outer$StaticInner(){}
}
The main difference between static and non-static inner classes is that a non-static inner class has access to other members of the outer class, even if they are private. Non-static inner classes are a "part" of the outer class. You cannot create nor can they exist without an instance of an outer class. A consequence of this is that an instance of a non-static inner classes are destroyed when the outer class's instance is destroyed.
Static inner classes, on the other hand, are just like normal outer classes. The live and die on their own. You don't need an instance of the outer class for the inner class to exist. That means they also have their own life cycle. They get destroyed when the garbage collector decides to destroy them.
How does this affect memory and/or performance? I really don't know. :)
Static inner classes (i.e. classes declared inside another class with keyword static) are quite similar to "normal" classes except you don't pollute your package's name space. That is their (only) difference and benefit and I believe that's the reason you see it in Android.
Use static inner classes when the purpose of the class is tighten to the main class, but does not depend on its instances. This is generally considered as a good practice.
A non static inner class instance holds a reference to the outer class instance while a static inner class instance does not.
This is relevant for the applications memory footprint as the hidden reference may lead to memory leaks - the garbage collector cannot collect the outer class instance until no more references exist. Also the additional reference itself needs memory, this may be relevant if a high number of instances are used.
class Outer{
class Inner{//Only works with non static inner class
public Outer getOuter(){return Outer.this;}
}
}
It is also relevant for its use, the reference to the outer class is a ctor argument of the inner class, to create a new non static inner class object you have to call the ctor like a memberfunction on an instance of the outer class or from within a memberfunction of the outer class. This means that you cannot have a instance of the inner class without an instance of the outer class.
Outer.Inner in = new Outer().new Inner();
If you decompile an inner class (or watch it using debugger) you can see that there is generated code for accessing the instance of the outer class that was used to create them. The overhead for this is more memory for the additional pointer, more cpu for garbage collection because of additional pointer to test, and if you want to nit pick, longer compile time. Creating instances of non static inner classes is a bit more complicated because you need an instance of the outer class to create them.
Visibility of both static and non-static inner classes can be controlled. Usually they are private if their implementation is strongly connnected to internal details of the outer class, and the developer doesn't think the code can be reused. In this sense they are not better than private functions. Inner classes might be public in cases like Map.Entry, where the inner class is strongly connected to the interface exposed by the class, and the developer doesn't think that Map.Entry can be used without some kind of a Map. Both types have access to private members of the outer class and the outer class has access to private members of the inner class.
Instances of static and non-static inner classes are garbage collected like every other class. There is no special connection between the grabage collection of the outer class and the garbage collection of the inner class.
In the case of UI classes implementation like swing or android you will see static inner classes because they are treated like private function. These classes are not developed for reusability outside the outer class and are strongly connected to the internal implementation of the outer class. There is no reason to expose them and to make sure they can work in more cases than the specific context of the outer class requirements.

How do you resolve a circular dependency with an inner class?

(Java question)
If I reference a field in an inner class, does this cause a circular dependency between the enclosing class and the inner class?
How can I avoid this?
Here is an example:
public class Outer {
private Other o;
private Inner i;
public Outer() {
o = new Other();
i = new Inner() {
public void doSomething() {
o.foo();
}
};
}
}
Static vs instance class: If you declare the inner class as static then the instances of the inner class doesn't have any reference to the outer class. If it's not satic then your inner object efectivelly points to the outer object that created it (it has an implicit reference, in fact, if you use reflection over its constructors you'll see an extra parameter for receiving the outer instance).
Inner instance points outer instance: Circular reference is in case each instance points the other one. A lot of times you use inner classes for elegantly implementing some interface and accessing private fields while not implementing the interface with the outer class. It does mean inner instance points outer instance but doesn't mean the opposite. Not necesary a circular reference.
Closing the circle: Anyway there's nothing wrong with circular referencing in Java. Objects work nicely and when they're not more referenced they're garbage collected. It doesn't matter if they point each other.
The syntax you're using in the example is a little off there is no declaration of the class or interface Inner. But there isn't anything wrong with the concept of the example. In Java it will work fine.
I'm not sure what you're doing here, but you may want to consider a more simple design for maintainability etc.
It's a common pattern for anonymous event handlers to reference elements of their parent class, so no reason to avoid it if that's the case, that's how Java was designed instead of having function pointers.
(Not sure if this is what you are asking...)
At runtime, the inner class has an implicit reference to the instance of the outer class it belongs to. So whenever you pass the inner class instance around, you are also passing the outer class instance around.
You can avoid that by declaring the inner class as "static", but that means that the inner class can't access member variables of the outer class. So in that case if you want to access a member of the outer class, you need to pass it explicitly to the inner class (using a setter or using the constructor of the inner class).

Categories

Resources