I am using a MVC model and am trying to create a thread in the controller. When I am in the inner class run() I need to get the correct model but it is throwing a null pointer.
Here is the code to create the inner class and thread from the outer controller:
Thread thread = new Thread(new runWithThread(OpsSec, AmToChange, AgentID, balance, currency, selected_account_obj));
thread.start();
Inside the runWithThread I try to get the correct Model. AMModel is the Model class and withdraw is a method inside it. getModel is defined in the abstract controller I am extending(implementation inheritance).
((AMModel)getModel()).withdraw(10, "USD");
It works in the outer class but not in the inner class and I am not sure why I am getting the null pointer with the ((AMModel)getModel()). Any help would be appreciated.
Thanks
I realized the error. I had "extends AbstractController" in both the controller outer class and in runWithThread inner class. I am using Rational Arch and it didn't flag anything so I didn't notice the error.
I know this is pretty old, but try AMModel.this.withdraw(10, "USD");. Here's a generic example:
class Outer
{
class Inner
{
public void test()
{
Outer.this.variable = 1;
}
}
public int variable = 0;
private Inner inner;
}
After calling inner.test(), variable would be 1.
Related
Use case is something similar to below code. There is a class(Inner_Demo) inside another class(Outer_Demo). Inner_class will be instantiated upon some condition in the outer class private method.
class Outer_Demo {
public Outer_Demo() {
test();
}
// private method of the outer class
private void test() {
Inner_Demo demo;
if(condition)
demo = new Inner_Demo();
}
// inner class
class Inner_Demo {
}
}
main(){
Outer_Demo outer = new Outer_Demo();
// Here I need to check is Inner class got instantiated
// Trying to print the value as below leads to error create
// field/constant Inner_Demo in Outer_Demo
System.out.println(Outer_Demo.Inner_Demo); // outer.Inner_Demo
/* Storing the created instance to Outer_Demo.Inner_Demo
is allowed */
Outer_Demo.Inner_Demo inst = outer.new Inner_Demo();
System.out.println(inst);
}
I need to test, Is inner class is Instantiated or not. I got to know that calling the inner class in above way is incorrect.
Reflection might have used if the field demo in the Outer_Demo class's method test is not local/ have class level access.
Can anybody help me to understand, Is there any way find inner class status. Any links to subject is helpful. Thanks.
You probably want to check if an object of that class has been instantiated.
For this task you should declare an Inner_Demo field in your Outer_Demo class:
class Outer_Demo {
public Outer_Demo() {
test();
}
Inner_Demo innerDemo;
...
Now, each time the object is instantiated, this field must be assigned a value:
innerDemo = new Inner_Demo();
And finally, when you want to check if the object exists, you just do it like:
if (innerDemo == null) {
//object does not exist yet and has to be instantiated
} else {
//object does exist and can be used
}
Say if I have a dropdown in a form and I have another nested class inside of this class .
Now what's the best way to access this dropdown from the nested class?
Unlike Java, a nested class isn't a special "inner class" so you'd need to pass a reference. Raymond Chen has an example describing the differences here : C# nested classes are like C++ nested classes, not Java inner classes.
Here is an example where the constructor of the nested class is passed the instance of the outer class for later reference.
// C#
class OuterClass
{
string s;
// ...
class InnerClass
{
OuterClass o_;
public InnerClass(OuterClass o) { o_ = o; }
public string GetOuterString() { return o_.s; }
}
void SomeFunction() {
InnerClass i = new InnerClass(this);
i.GetOuterString();
}
}
Note that the InnerClass can access the "s" of the OuterClass, I didn't modify Raymond's code (as I linked to above), so remember that the "string s;" is private because no other access permission was specified.
Nested types aren't like inner classes in Java - there's no inherent instance of the containing type. (They're more like static nested classes in Java.) They're effectively separate classes, with two distinctions:
If the containing type is generic, the nested type is effectively parameterised by the containing type, e.g. Outer<int>.Nested isn't the same as Outer<string>.Nested.
Nested types have access to private members in the containing type.
Unlike Java, in C# there is no implicit reference to an instance of the enclosing class.
You need to pass such a reference to the nested class. A typical way to do this is through the nested class's constructor.
public partial class Form1 : Form
{
private Nested m_Nested;
public Form1()
{
InitializeComponent();
m_Nested = new Nested(this);
m_Nested.Test();
}
private class Nested
{
private Form1 m_Parent;
protected Form1 Parent
{
get
{
return m_Parent;
}
}
public Nested(Form1 parent)
{
m_Parent = parent;
}
public void Test()
{
this.Parent.textBox1.Text = "Testing access to parent Form's control";
}
}
}
Static Members
Since no one has mentioned it so far: Depending on your situation, if the member variable can also be static, you could simply access it in following way.
class OuterClass
{
private static int memberVar;
class NestedClass
{
void SomeFunction() { OuterClass.memberVar = 42; }
}
}
Sidenote: I marked memberVar purposefully (and redundantly) as private to illustrate the given ability of the nested class to access private members of it's outer class.
Caution / Please consider
In some situations this might be the easiest way/workaround to get access, but ...
Static also means, that the variable will be shared across all instance objects, with all the downsides/consequences there are (thread-safety, etc.)
Static also means, that this will obviously not work if you have more than one instance of the parent's class and the variable should hold an individual value for each instance
So in most cases you might wanna go with a different approach ...
Passing a Reference
As most people have suggested (and because it is also the most correct answer), here an example of passing a reference to the outer class' instance.
class OuterClass
{
private int memberVar;
private NestedClass n;
OuterClass() { n = new NestedClass(this); }
class NestedClass
{
private OuterClass parent;
NestedClass(OuterClass p) { parent = p; }
SomeFunction() { parent.memberVar = 42; }
}
}
One other method, which is useful under certain circumstances, is to derive the nested class off of the outer class. Like so:
class Outer()
{
protected int outerVar;
class Nested() : Outer
{
//can access outerVar here, without the need for a
// reference variable (or the associated dot notation).
}
}
I have used this technique especially in the context of Structured Unit Tests. (This may not apply to the OP's particular question, but it can be helpful with nested classes in general, as in the case of this "duplicate" question: " Can i access outer class objects in inner class ")
You could pass the enclosing class as a parameter to the nested class constructor, like this:
private NestedClass _nestedClass;
public ParentClass()
{
_nestedClass = new NestedClass(this);
}
Nested classes are generally not recommended and should be private and/or internal. They are, in my opinion, useful sometimes though.
Correct me if I am wrong, you are trying to process the outer control from inner class hence you ran into this. A better way of doing this would be to handle affairs in a event driven fashion. Use an Observer pattern, Register a listener on the outer control (your nested/inner class will be the listener). Makes life simpler. I am afraid that this is not the answer you were expecting!
send the master class as an constructor parameter to the nested (inner) class.
there is a good answer above but I like to write sth.
c# nested class is by default private
private to containing class if your want to use it must be public
My Inner and outer class file here:-
package com.demo;
public class Outer {
int outer_x=100;
void test(){
Inner inner =new Inner();
inner.display();
}
public class Inner {
void display(){
Outer ob=new Outer();
ob.test();
System.out.println("display: outer_x= "+outer_x);
}
}
}
Another main class acess outer class member :-
package com.demo;
class InnerClassDemo{
public static void main(String args[]){
Outer outer=new Outer();
outer.test();
}
}
Exception:-
Exception in thread "main" java.lang.StackOverflowError
at com.demo.Outer.<init>(Outer.java:3)
at com.demo.Outer$Inner.display(Outer.java:12)
at com.demo.Outer.test(Outer.java:8)
How can resolve this issue ,pls give me any idea?
Your test method creates an Inner and calls its display() method, which creates an Outer and calls its test method. Nothing in your code stops this from continuing forever, until enough methods have been called to fill up the stack space and a StackOverflowError occurs.
Either don't have test call display, or don't have display call test.
I resolved this issue from #rgettman answer modified my Inner and outer class here
package com.demo;
public class Outer {
int outer_x=100;
void test(){
Inner inner =new Inner();
inner.display();
}
public class Inner {
void display(){
System.out.println("display: outer_x= "+outer_x);
}
}
}
Outer.test calls Inner.display which calls Outer.test which calls Inner.display which calls Outer.test which calls Inner.display which...
This goes on until your program runs out of stack space.
You get StackOverFlowError, because your call has a infinite method call which always exceeds program stack.
Your test method calls display and display method calls testunconditionaly.
It is the basic requirement to define a base case for recursive methods, so you should define a base case which will return and stop recursive method calls.
See also
Recursion
I have a public class with a private class inside it:
public class Out
{
private class In
{
public String afterLogic;
public In(String parameter)
{
this.afterLogic = parameter+"!";
}
}
}
And wanted to test the In class with jMockit. Something along these lines:
#Test
public void OutInTest()
{
Out outer = new Out();
Object ob = Deencapsulation.newInnerInstance("In", outer); //LINE X
}
The problema is, in LINE X, when trying to cast ob to In, the In class is not recognized.
Any idea how to solve this?
Thanks!
The only constructor in class In takes a String argument. Therefore, you need to pass the argument value:
Object ob = Deencapsulation.newInnerInstance("In", outer, "test");
As suggested in the comment one way is to change the access modifier of the inner class from private to public.
Second way (in case you don't want to make your inner class public), you can test the public method of outer class which is actually calling the inner class methods.
Change the scope of the inner class to default then make sure that the test is in the same package.
There are two approaches, first as mentioned in other posts to change the scope to public. The second which I support is, to avoid testing private class altogether. Since the tests should be written against testable code or methods of the class and not against default behavior.
I have a code snippet as
public class ThreadStates {
private static Thread t1 = new Thread("T1") {
public void run() {
try {
sleep(2);
for (int i = 100; i > 0; i--) ;
} catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
.......And rest of code follows.
What type of declation is step 1. I can see that we have no inherited Thread class in ThreadStates class, then why run() method declaration is coming. PLease clarify what is happening.
You have created an anonymous inner class which inherits from Thread (note the { directly following new Thread(). You are giving this class a run method, and storing it in t1.
It's called an anonymous inner class. When you say 'new Thread("T1") { ... }', you're effectively defining a new subclass of Thread.
Is this a variation of an anonymous inner class?
http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
When you call a class that directly implements the Runnable class, you immediately inherit all the methods that said class does. Thread is one of the classes that implements Runnable and it makes you implement the run()method which is an abstract one.
That's why it shows the run()nethod there.