Instantiation of Outer Class From Inner Class Instance? - java

I have found below example in one of the answers:
Java inner class and static nested class
public class Container {
public class Item{
Object data;
public Container getContainer(){
return Container.this;
}
public Item(Object data) {
super();
this.data = data;
}
}
public static Item create(Object data){
// does not compile since no instance of Container is available
return new Item(data);
}
public Item createSubItem(Object data){
// compiles, since 'this' Container is available
return new Item(data);
}
}
I want to know why we do something like this: i.e. To get the instance of container why we create the instance of inner class? What is the use of this approach? Which design pattern it is?
The above approach is already being used in one of the maintainance project, and I still didnt get whats the use of it?

The main purpose of this construct is the management of data. That the inner class hands out references to the "container" is just an unimportant implementation detail.
The problem with abstract and abridged examples like yours is: You just transfer the "how" from the writer to the reader of the code. But the "why" is completely lost.
So you can just replace Container with FileSystem and Item with File and data with some more internal state to a file. Then you can see:
A filesystem can have one or more files.
A file is exactly in one filesystem.
The lifetime of the File cannot exceed the lifetime of the filesystem.
The implementation between File and Filesystem is tightly coupled - each one might call the other - even private methods.
The last point is IMO the most important one: You can offer the slim and safe public API to the real user while File and Filesystem can use dangerous private methods of each other. In case of a Filesystem you don't want to grant anyone else access to these dangerous methods.
These traits are common for some problems - hence they are used.

I want to know why we do something like this: i.e. To get the instance of container why we create the instance of inner class?
That is not what is happening.
In fact, you cannot create the instance of the inner class Item unless you already have an instance of the outer class Container on which you can call the createSubItem method. Creating the inner class instance doesn't create a new instance of the outer class. Rather it creates it in the context of the existing instance ... the one that is "available" when you invoke the inner classes constructor.

the method in question is defined as static so it can access only static members of the class and since the Item class is not declared as static inner class it can't be accessed from a static function.
I am not sure about this specific design pattern or why it is required but this can work:
public static Item create(Object data) {
Container c = new Container();
return c.new Item(data);
}
One of the places we have used such design is just for having additional Comparator classes.

Related

Access un synchronized map from multiple classes

This question came up out of curiosity , i have three classes A, B and C .
class A has a member variable Map say sharedMap
class B and class C is accessing Class A's sharedMap and trying to change the values of the map as per their needs.
The problem is- I cant change anything in class A as i don't have control on class A (can not use synchronize keyword or method to synchronize the Map) is there any way to still manage the synchronization of class A's sharedMap?
Use composition - instead of creating an instance of A just wrap it inside some other class and expose the map using a synchronized method. If A is implementing some interfaces then that wrapping class should also implement them and just delegate all the calls to A. So basically something like
class WrappedA implements InterfaceA {
private A inner = new A(); // don't expose A's instances to other classes
public synchronized void mapManipulator() {
// do something with inner.map
}
#Override
public void interfaceMethodA() {
// IF any of those methods are using the map, remember to synchronize
inner.interfaceMethodA();
}
}
Since it's your code you can make such a change. If you can't make even that (something else is creating A?) then A will always be exposed to other classes so you have to just make a convention that all other classes will call it through some new class but this will be very error prone if someone forgets to use the wrapper instead of A.
Any more details regarding the context might help to come up with something better...

How to deal with arrays of static objects?

I'm having an issue dealing with static object types in a parser I'm writing.
glob = new func("glob");
glob.addChild(new func("wrong"));
System.out.println(glob.name);
func is a static class that I'm referencing in the above code within main. When this code is run, the printed text is "wrong". I'm assuming that making func static as I did is causing there to only ever be one func allowed, and it's being overwritten since I can't create instances of func. Is there a way around this? Here's part of the code for the declaration of func for reference
static class func{
public func (String name){
//etc
}
}
This is becoming an issue because I want to be able to create a nest of these objects to use for determining scope within a parser. func would have children, and the idea was that a child node could look for a 'variable' (here just a string) that I add first within itself, then within its parent, and so on down the line. Creating children just overwrited the parent though.
Update: People wanted more code from func
static class func{
public static func[] children;
public String name;
public static func parent;
private static int child_index, var_index;
private static String[][] vars;
public func (String name, func parent){
children = new func[50];
//etc
}
}
You're right that I did have a static name. If I remove that, my worry is that the vars/children arrays will still continue to be overwritten, and removing those gives me a lot of 'non-static variables cannot be referenced...' messages.
The static modifier on a class doesn't do the same thing as static on other entities. First of all, you can't apply static to a top-level class at all. It's only useful for a class defined inside another class:
public class Outer {
public class Inner {
...
}
static public class Nested {
...
}
}
The difference is that whenever you create an object of class Inner, the object "belongs", in a sense, to some object of an Outer class. The Inner object contains a reference to some Outer object, and its methods can reference fields of the Outer object to which it belongs.
The Nested class, however, is more like a top-level class; the main difference is that outside classes can refer to it as Outer.Nested, which can be useful when you want several different nested classes all named Nested. It's a way to avoid "polluting the namespace" with top-level class names, and to make it clear that a Nested is somehow closely related to an Outer. Also, because of Java's rules about visibility, a Nested class's methods can access private members of Outer, which an outside top-level class can't do.
But it doesn't mean you can create only one Nested. If you want a class that can have only one object, use a singleton pattern. (But also think about whether you really want to do this and why; singleton patterns are disdained by some programmers, probably because they look too much like global variables, which reduces the flexibility to make certain kinds of changes to your program in the future.) (P.S. After trying to read your question more carefully, I'm not sure that a singleton is what you want, and in fact I'm not clear at all on what your design is supposed to look like.)
It is meant to be so, since a static variable is a variable owned by a Class and not instances of that Class and it is so for inner static classes.
Otherwise I can't see how did you manage to make your func class static since as far as I know Java do not allow Top-level classes to be static and only inner classes can be so.
I can't see clearely what you are aiming to achieve but you should reconsider your design. Maybe with better explanation someone could bring some help.

What is the purpose of an inner class

I am reading about inner classes in an interface and class. I could not understand about the real use. However I dont want to discuss anything about inner classes inside an interface in this post.
I have used inner classes as a callback till now. I can do the same declaring the class outside somewhere.
Suppose that I have a list of students and I want to sort them by id. I have to implement Comparator interface and provide it as an argument to Collections's sort method.
public class StudentList {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
Student student = new Student();
student.setId(1);
student.setName("Krishna");
students.add(student);
student = new Student();
student.setId(2);
student.setName("Chaitanya");
students.add(student);
Collections.sort(students, new StudentList().new MyComparator());
}
public class MyComparator implements Comparator<Student> {
#Override
public int compare(Student o1, Student o2) {
if (o1.getId() < o2.getId()) {
return 1;
} else if (o1.getId() > o2.getId()) {
return -1;
} else {
return 0;
}
}
}
}
I can do the same like this also
public class StudentList {
public static void main(String[] args) {
List<Student> students = new ArrayList<Student>();
Student student = new Student();
student.setId(1);
student.setName("Krishna");
students.add(student);
student = new Student();
student.setId(2);
student.setName("Chaitanya");
students.add(student);
Collections.sort(students, new MyComparator());
}
}
class MyComparator implements Comparator<Student> {
#Override
public int compare(Student o1, Student o2) {
if (o1.getId() < o2.getId()) {
return 1;
} else if (o1.getId() > o2.getId()) {
return -1;
} else {
return 0;
}
}
}
I dont think inner class in the above example adds any significant importance unless it is declared as a private class. When I declare it as private, only the enclosing class can use it. It means the class is strongly binded with the enclosing class and I see some advantage of having so.
Can anyone please explain me the true importance/significance of using/writing inner classes in an application.
You should inner classes if you need something specific to the class your working with. A good example of an inner class can be found here: java.awt.geom.Ellipse2D and the corresponding Ellipse2D.Double and Ellipse2D.Float (Ellipse2D source code). You could place those classes in a package, but they make a lot more sense as nested classes. They directly correspond to Ellipse2D and will have no use elsewhere; also, the fact that they are nested improves readability in code that uses them. On another note, if an inner class is very likely to be useful when more general, it is often better to generalize it and make a regular class.
Also, inner classes can directly access variables in the outer class. That means that an inner class can be used to change the outer class. It is still possible to get an instance of it to be used outside of either class. To illustrate what I am saying:
public class Example {
public static void main(String[] args) {
Foo foo = new Foo();
Foo.Bar bar = foo.getBar(); //note, cannot call new Foo.Bar(); as Bar is dependent on Foo
for (int i = 0; i < 50; i++){
System.out.println(bar.get());
}
}
}
class Foo {
int val;
Bar b;
public Foo(){
b = new Bar();
}
public Bar getBar(){
return b;
}
public class Bar{
public Bar(){
val++;
}
public int get(){
return val++;
}
}
}
Another possible use of inner classes is to create something like a wrapper class for an the truly wanted inner class, especially useful for a recursive class. This is used for implementing a LinkedList. At one time, I implemented such a list, not realizing that anything of the sort had been made before. The idea is that you have your LinkedList class, and a Node class within it (where each node only points to the next/previous node and holds a single value). Doing it this way simplifies the code. However, it doesn't make any sense for the Node class to be external to LinkedList, because what type of "node" would it be? Thus it should be an internal class.
There are two advantages that I see. I haven't used them myself too much so there are just my observations.
If inner class is very small, it might be more easy to define as inner rather than creating a separate file for it. It would help in manageability in big projects which already have too many files.
Second, if inner class can only be used in it's parent class's context, defining it as inner class would give it namespace containing parents class.
public class FileProcessor {
public class Output {
//will be namespaced as FileProcessor.Output, more readable.
}
}
From answer Inner Class. What is its purpose?
So what does this gain us? Well, the inner class instance has access
to the instance members of the containing class instance. These
enclosing instance members are referred to inside the inner class via
just their simple names, not via this (this in the inner class
refers to the inner class instance, not the associated containing
class instance)
Also see What are the uses of inner classes in Java? Are nested classes and inner classes the same?
Some classes don't make make much sense on their own - they only make
sense in the context of another class. Inner classes are helpful at
defining this kind of relationship - they allow the developer to
express the relation between highly cohesive classes more explicitly.
see more
As an example consider a Node in a Graph. A Node has a list of peer
Nodes which it can reach itself. It makes sense to define a Peer class
as an inner class of Node. For example:
public class Node
{
private String name;
private List peers = new ArrayList();
private Node( String name )
{
this.name = name;
}
/**
* Represents a peer node that is reachable from this node
*/
class Peer
{
private Node node;
private int distance;
}
}
Purpose of Inner class
Inner classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
Nested classes can lead to more readable and maintainable code because it logically group classes in one place only.
An example of when inner classes are necessary
Suppose you have a Java GUI (Graphical User Interface) class that acts as a chat client like Gchat or Facebook Chat. Think about what methods would need to be present in a class like that which represents a chat client – you will need a method that will read user input from the chat box, methods to actually send the user input to the server and to whoever the user is chatting with, even a method that detects that you are typing so that Gchat can display the “XZY is typing” text to your friends, etc.
There are two types of methods needed in our example
So, it should be clear that there will need to be two different types of methods that will drive your chat client application: 1. Chat client specific methods like those that will read user input from the chat box and send user input to the server. 2. Event handling methods that will respond to actual events that occur in the chat client window – like hitting the “RETURN” key, detecting consistent typing, etc.
Because it’s clear that there will need to be two different types of methods, then from an Object Oriented Design perspective, it seems like we should have two different classes: one class for the chat client specific methods and one class for the event handling methods. That does follow the normal object oriented design practices – because we are creating classes that specialize in what they do.
The problem with having two separate classes
But, in this particular example, there is a problem with having two separate classes. And that problem is the fact that the event handling code is very much related/tied to the code that belongs to the chat client. This makes sense, as we talked about earlier with our GChat example; as soon as a user in GChat hits “RETURN” or “ENTER” on the keyboard that should trigger an event, which should then grab the text from the chat client window. And, the chat client window would be a particular instance (basically an object) of the chat client class. For example, if you are talking to your friend Bob in GChat, he will have one window in Gmail and you will have one window open in Gmail, and each window is an object of the chat client class. So there will be two separate objects of the chat client class – one for you and one for Bob.
Now, if Bob types something and hits the RETURN key, the event handler code that responds to the RETURN key being pushed will need to be able to communicate with Bob’s chat client class object so that it can grab the text from Bob’s chat client class window, or the text field where that text is actually stored. The key here is thinking in terms of objects – an object of the chat client class is created for each person using GChat, so you will have your own object and Bob will have his own object. This means that the event handling code will need to access an chat client object’s text field – which is a member of the class, and an instance variable. So, it should be clear that the event handling code needs access to the members of a chat client class object in order to be able to effectively help.
Why don’t we just combine the event handling code with the chat client code?
Combining the event handling methods with the chat client specific methods in one big class sounds like a good idea at first, but there is one big problem: If both the event handling code and the chat client code need to inherit some code from different classes then you are in trouble, because Java does not support multiple inheritance – meaning that our one “big class” can not inherit from two different classes.
Inner classes to the rescue
Now, this is why inner classes were created – for situations exactly like the one we described above. An instance of an inner class can access members of an instance of the outer class, because an inner class is just another member of the outer class. And, inner classes can even access the private members of the outer class – yes you did read that correctly!
Read this - When should inner classes be used in Java?
Static Inner class reaches private static fields of Outer classes. It means that if I extend Outer.Inner class anywhere,(because Inner is static, I don't have to make object before extend) I cannot reach the private fields of Outer class. This is perfectly good for context security.
1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
I will give my explanation from a different point of view. Please first check out the memory model of Java's inner class. Then with some basic skills in programming, you will know why bother using inner class.
See How inner class object resides in memory?
Besides, usually you should instantiate the inner class object in outer class's constructor to "make sense", and sometimes you can provide a getter method to retrieve the inner class instance which resides in outer class instance if you really want to mess with that inner class instance.

Android and Java and data classes

I am relatively new to working with Java and have come from a C/C++ background.
In my app I am needing a number of classes which will simply hold data.
Rather than have one file per data class, I thought of simply putting all the classes inside a basic class.
Here is what I am declaring -
public class InternalData
{
public class LocalSearchDef
{
public String m_sAdresse = null;
public GeoPoint m_gpPoint = null;
public int m_iSearchRadius = 0;
}
public class GeoBounds
{
public double m_dNELat;
public double m_dNELng;
public double m_dSWLat;
public double m_dSWLng;
}
}
However, eclipse tells me that there is "No enclosing instance of type InternalData is accessible. Must qualify the allocation with an enclosing instance of type InternalData (e.g. x.new A() where x is an instance of InternalData).", when I try to create a new instance of, say, GeoLocation I get the error.
This happens with either :
GeoLocation gl = new GeoLocation();
or
GeoLocation gl = new InternalData.GeoLocation();
Can anyone point me in the right direction please ?
You would need to make the internal classes static.
public static class Foo {
}
Although you can do it using a static declaration, don't try to do it this way.
If you are going to encapsulate classes within another, they should have some relationship to the enclosing class (like Map.Entry to Map). You are simply trying to organize multiple classes into the same file by making a holder class, that serves no purpose.
There is nothing wrong with one class per file, this is the standard Java approach. You need to justify why they should be in the same file, not the other way around.
You may also want to declare your classes with accessor methods not simply create data structs with all public access to the data members. This is poor OO.
You're trying to use a non-static inner without an instance of InternalData for it to belong to.
See: An enclosing instance that contains <my reference> is required

Java member object inside class of same type

I am looking at a codebase and I often see something like:
public class SomeClass
{
protected static SomeClass myObject;
//...
public static SomeClass getObject()
{
return myOjbect
}
}
I'd like to make sure I understand the purpose behind this. Is it to ensure one instance of the class gets shared even if it is instantiated multiple times? I am not sure about the vocabulary here, or else I'd search for the answer, so if this pattern has a name, please let me know.
Also, this seems a little chicken-and-egg definition because the class includes an object of the type of the class. Why isn't this actually paradoxical?
Thanks!
This is really only common with the Singleton Pattern where there is only this one instance of the class. While it has its uses, Singleton is over- and misused more often than not (usually to disguise procedural programming as OO). It also occurs very often in example code for Java AWT or Swing, where you typically subclass Frame / JFrame, and create an instance in a main method inside the same class.
Also, this seems a little
chicken-and-egg definition because the
class includes an object of the type
of the class. Why isn't this actually
paradoxical?
Why do you think it is? The class mainly describes what members instances of this type have - but a static member does not belong to an instance, it belongs to the class itself, so it doesn't have anything to do with the "blueprint" role of the class. Static members are really somewhat un-OO because of that.
But even on the instance level you can have references of the same type. For example, an entry in a linked list would typically have two references to the next and previous entries, which are of the same class.
This is called the Singleton design pattern.
You are correct in stating that the purpose is to ensure only one instance of the class gets created.
Wikipedia has a preyty good article on the pattern.
The pattern you mentioned is called "Singleton", but from your code sample it is not clear if this is really what is intended. Due to the fact that the member is protected, I would guess not - if there are subclasses, then there would probably not be a single instance.
It's called Singleton. You ensure the creation of just ONE (1) object of a given class.
You should add a private Constructor, so the only one who create the object is the class.
public class SomeClass
{
// Using private constructor
protected static SomeClass myObject = new SomeClass();
private SomeClass(){
//...
}
public static SomeClass getObject()
{
return myOjbect
}
}
Much much more here, in Wikipedia
You may want to take a look to Factory Pattern
It's not all that uncommon; it can be a good way to implement the Singleton pattern. There can be other uses as well - sometimes you will want a handful - and no more - of objects of a given class; that class is a good place to hang onto them. In the event that you don't want other classes to be able to create objects of this class, it is common to give the class a private constructor as well.
It's not paradoxical, because the compiler can be aware of a reference to the class before it has fully compiled the class. Later - if you like to think of it this way - it can "fill in the blanks".

Categories

Resources