Call a non static void from another class - java

I am trying to end an never ending circle. I need to call a void that is not static from another class. The reason that I do not make it static is that some things are very hard to make static. (Everything inside a static void needs to be static).
I am trapped in a circle where I need to call a non static void from another class. I can not make it static because it some code do not like to be passed.
Till now I solved it sort of by a handler:
public static void change(){
//This is called to change a boolean
start=true;}
private void startDone(){
int timeBetweenChecks = 50;
final Handler h = new Handler();
h.postDelayed(new Runnable(){
public void run(){
if (start==false){
startDone();
} else{
//Do something
}
}
}
}, timeBetweenChecks);
};
The problem with this is that I have to run a handler that is checking if something has changed pretty often(In my case).
Is there any way of calling the non static startDone() directly?

If you are asking if there is a way to call a non-static method of a class without instantiating an object of that class, then no.
If I don't own a dog, I cannot tell my dog to sit.

The answer to your question is: No, you cannot call a non-static method from a static method without an instance of the class containing the non-static method.
To solve your problem: maybe the best way would be to broadcast an intent from change().
Something like:
public static void change(Context c){
start=true;
c.sendBroadcast(new Intent("CHANGE_HAS_BEEN_CALLED"));
}
Then in the non-static code of your activity you can register a receiver like this:
IntentFilter filter = new IntentFilter();
filter.addAction("CHANGE_HAS_BEEN_CALLED");
registerReceiver(new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
if (start==false){
startDone();
} else{
//Do something
}
}
}, filter);

By definition, if startDone() is non-static, then it makes no sense to call it unless you've instantiated the class that contains it. A non-static method is an instance method, which means it can return a different result for every object of its enclosing type.
I think what you want is a class that only contains startDone(). You want to instantiate the class once for your entire application, and then be able to call startDone().
Suppose the class is called ItsDone. Instantiate it as a singleton, then return the singleton when you do a "new", and call startDone().

a handler that is checking
if something has changed pretty often (In my case).
Sounds like callback to me. You pass a piece of code to that "something", and this piece of code is executed by "something" whenever its state changes. If you have control over this "something", it's very easy to implement such behavior, if you don't (if "something" is a part of some library), it probably has this behavior implemented (of course, if it is well-designed).
Anyway, checking the state "something" by querying it every, say, 50 ms is not the way to go.

The accepted answear for this question is a better solution then the solutions that are already sugested. Hope this will help anybody googling.

Related

Why is subclass field initialized to its default value within super constructor? [duplicate]

I ran into an interesting problem yesterday and while the fix was quite simple, I'm still a bit fuzzy on the "why" of it.
I have a class that has a private member variable that is assigned when it is instantiated, however if it is used in an abstract function that is called by the super class's constructor, the variable does not have a value. The solution to the problem was quite simple, I simply had to declare the variable as static and it was assigned correctly. Some code to illustrate the problem:
class Foo extends BaseClass
{
private final String bar = "fooBar!";
public Foo()
{
super();
}
#Override
public void initialize()
{
System.out.println(bar);
}
}
And the base class:
abstract class BaseClass
{
public BaseClass()
{
initialize();
}
public abstract void initialize();
}
In this example, when we call new Foo(); it will output (null) instead of the expected fooBar!
Since we're instantiated an object of type Foo, should its members not be allocated and assigned prior to calling its (and consequently its super class's) constructor? Is this specified somewhere in the Java language or is it JVM specific?
Thanks for any insight!
The assignment of bar = "fooBar!"; is inlined into the constructor during compile time.
The superclass constructor runs before the subclass constructor, hence it would only be natural that the statement is executed afterwards.
Generally though, it's bad practice to call overridable methods from a constructor.
It is as defined by the Java Language Specification. Changing it to static will almost never be and acceptable solution in real world situation.
See JLS 4.12.5 Initial Values of Variablesand JLS 8.3.2 Initialization of Fields
Overall, it is bad practice to call a non-final method from a constructor. the reason being that it could (and if the method is abstract then definitely does) call method in the class that has not yet been initialized: When new Foo() is executed, the BaseClass initializer (constructor) gets called before the Foo constructor, so Foo.initialize is essentially working on an Object that has not been fully constructed yet.
There's just one thing I would like to add to the accepted answer, because I don't entirely agree with his conclusion.
We've all done this.
class Engine {
public Engine() {
init();
}
void init() {
lockDoors();
releasePressure();
tightenSeatbelts();
launchRocket();
}
...
}
Now the question is, which access modifier should we add to our init() function. Should it be private or protected.
make it private <-- keeps subclasses out
make it protected <-- allows subclasses in
Before you make a choice
Now first of all, you should realize that (almost) all code in the Engine class can be replaced by a subclass.
code in a public function, can easily be overridden
code in a protected function, can easily be overridden
code in a private function, can be replaced by overriding all methods that call it.
Well, there is just one exception:
you can never modify the code of a constructor
you can never avoid a private method being called from the constructor of a super class.
(and of course, you cannot replace a final method)
Protected init() - the wrong way
Let's say the init() method is protected there is indeed a pitfall. It is tempting to override it to add features as follows. That would indeed be a mistake.
class SubEngine extends Engine {
int screws = 5;
void init() {
tightenScrews();
super.init();
}
void tightenScrews() {
// this won't print 5, but it will print 0.
System.out.println("tightening " + screws + " screws");
}
}
Protected init() - the right way
So, basically, you should just disable the parents code and postpone execution to your own constructor instead.
class SubEngine extends Engine {
int screws = 5;
public SubEngine() {
initSubEngine();
}
void init() {
// disable parent code
}
void initSubEngine() {
tightenScrews();
super.init();
}
void tightenScrews() {
// this will print 5 as expected
System.out.println("tightening " + screws + " screws");
}
}
Private init() - you may need a phonecall
Now, what if the init() method is private ?
Like mentioned above, there is no way to disable the code of a parent constructor. And if init() is private you simply cannot disable it.
You'll end up copying the entire Engine class, perhaps just to add 1 line of code.
And that may not be the end of it. Even after copying your class, your copied object won't be an Engine meaning that you won't be able to use your EngineUtil#inspectEngine(Engine engine) function.
Perhaps somebody knew this in advance and made an IEngine interface. Then you can get away with it.
In practice it means you'll have to take your phone, and call to that other department that made the Engine class, and ask them to change their code a little to take away some restrictions.
Intelligent design
There is another way. Constructors are for setting variables. They shouldn't activate anything. Everytime you see a class creating a new Thread from their constructor (or through a private method) that should be a red flag.
class Engine {
public Engine() {
}
public void init() {
lockDoors();
releasePressure();
tightenSeatbelts();
launchRocket();
}
// and you probably also want one of these
public void shutdown() { ... }
...
}
Intention
Of course, your intention may very well be not to open up your code. Perhaps you really don't want to allow others to extend your classes. There certainly can be cases where you want to lock people out.
Be aware that it will also make it harder to write tests for your code.
Anyway that's a different scenario.

How to pass class method as a parameter before the instance is declared?

What I want to do is like this. My question is how can I call tm.test in inner.
// TestMain is a class implemented handler
public void outer() {
inner(TestMain::test); // call inner
}
public void inner(handler h) {
TestMain tm = new TestMain();
//invoke tm.h(), i.e. invoke tm.test() in this example
}
public interface handler<M> {
void entitySelector();
}
I know how to call tm.test in inner if tm is declared in method outer, i.e. pass the function as tm::test
But I have to declare the instance every time I call inner.
Simply spoken: you can't. And even it would be possible, you shouldn't do something like that.
There is the "principle of least surprise": you don't that people reading your code tell you "wtf?!" because your code surprises them.
In other words: you should step back and see if your design really makes sense this way. Can't you use a fixed tm instance for example; one that sits as field on your class; instead of being a local variable in your method?

Call non-static method int static class

I have a inner static class which extends thread inside my main Activity. In this Thread, I need to call a non-static method from my main Activity.
As I see, I have 2 options:
Make my non-static method static: This option would not be feasible cause inside this method I call startActivityForResult and I can't call this in a static way.
Create an object of my main Activity inside the inner static class, and call the method via this object.
MainActivity mActivity = new MainActivity();
//...
mActivity.method();
The one I'm using now is the second, but I have a doubt about it. If I do this, I understand that I'm creating a new instance of MainActivity, and doing this, are all definitions in onCreate method called? Or I'm just calling the method and the variables I'm using inside will be null?
UPDATE --
This is the inner class where I need to call the method from main. I need this to be static because the base functionality of the app needs it to be this way. Now I'm introducing a new method in main activity that must be called when an action happens inside the thread:
private static final class DetectionThread extends Thread {
//...
public DetectionThread(byte[] data, int width, int height) {
}
#Override
public void run() {
//DO STUFF HERE
//Action happens and calls the method from main activity:
SpeechWhenMotion();
//...
}
}
}
And this is the header of the method which is defined in the main activity. Inside of it I'm calling to another method which starts activity for result, so this is the reason why I cannot set this method as static:
public void SpeechWhenMotion() {
//...
}
Assuming MainActivity is the outer class, I guess what you are looking for is
MainActivity.this.startActivityForResult()
Creating another object isn't the right solution.
And BTW, it's equally bad to create a class extending Thread. I don't see a reason you need to do so. For all you need to do unless sophisticated threading, all you need to do is to implement Runnable(). Doing so properly segregate your threading concern from your business logic.
Pass a MainActivity instance to your static method. Then call .method() from that instance.
static void doSomething(MainActivity ma) {
ma.method();
}
This, or the 2nd option that you posted.

Difference between finish() and this.finish() in android

Providing finish() and this.finish() in onPause() or onStop() method is same?
Yes. Please become familiar with meaning of this. -> it's value is the reference to the current object. For example, if you have a class named Foo, and it has method named method(), then this in it would be a reference to a instance of the Foo (that is: a Foo object). Usually you do not need to use this.
this in any context refers to the containing class. So, if you are using the method inside an Activity, then this.finish() is same as finish(). However, if you are using this in a different class type, you may not have this.finish()
Even though the question is 3 years old.I prefer to torch some light over the present and future researchers.
this is just an object reference.You don't have to use this every time ,other than you need to get a reference of parent class from a child class instance.
Let's consider an example when using Thread class.
public class A
{
public A()
{
new Thread(new Runnable()
{
public void start()
{
B child=new B(A.this);//In this scenario,'A.this' refers to the parent class 'A' in which the 'Thread' class instantiated.If you simply pass 'this' ,then it would refer to the 'Thread' class as this statement executed in the current scope.
}
}).start();
}
}
public class B
{
A parent;
public B(A parent)
{
this.parent=parent;//'this' refers to the class B ,so that it can access the global variable 'parent' ,then assigns it with the local variable 'parent' passed through the constructor.
}
}
Like listed above ,there are different usages of this keyword.Its better to refer the oracle's documentation over here https://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
finish() and this.finish() is the same.
For the other part of the question, please read about the Activity lifecycle.
In your case It's the same. It's sometimes important to use this->... if you have an member and an method parameter with the same name like in the following example:
class foo{
int number;
void setNumber(int number);
}
so you can write in your method
void foo::setNumber(int number)
{
this->number = number;
}
And so It's clear which element you have used. But be careful don't use the same names it's not really nice.

Why are member objects initialized after the super class's constructor?

I ran into an interesting problem yesterday and while the fix was quite simple, I'm still a bit fuzzy on the "why" of it.
I have a class that has a private member variable that is assigned when it is instantiated, however if it is used in an abstract function that is called by the super class's constructor, the variable does not have a value. The solution to the problem was quite simple, I simply had to declare the variable as static and it was assigned correctly. Some code to illustrate the problem:
class Foo extends BaseClass
{
private final String bar = "fooBar!";
public Foo()
{
super();
}
#Override
public void initialize()
{
System.out.println(bar);
}
}
And the base class:
abstract class BaseClass
{
public BaseClass()
{
initialize();
}
public abstract void initialize();
}
In this example, when we call new Foo(); it will output (null) instead of the expected fooBar!
Since we're instantiated an object of type Foo, should its members not be allocated and assigned prior to calling its (and consequently its super class's) constructor? Is this specified somewhere in the Java language or is it JVM specific?
Thanks for any insight!
The assignment of bar = "fooBar!"; is inlined into the constructor during compile time.
The superclass constructor runs before the subclass constructor, hence it would only be natural that the statement is executed afterwards.
Generally though, it's bad practice to call overridable methods from a constructor.
It is as defined by the Java Language Specification. Changing it to static will almost never be and acceptable solution in real world situation.
See JLS 4.12.5 Initial Values of Variablesand JLS 8.3.2 Initialization of Fields
Overall, it is bad practice to call a non-final method from a constructor. the reason being that it could (and if the method is abstract then definitely does) call method in the class that has not yet been initialized: When new Foo() is executed, the BaseClass initializer (constructor) gets called before the Foo constructor, so Foo.initialize is essentially working on an Object that has not been fully constructed yet.
There's just one thing I would like to add to the accepted answer, because I don't entirely agree with his conclusion.
We've all done this.
class Engine {
public Engine() {
init();
}
void init() {
lockDoors();
releasePressure();
tightenSeatbelts();
launchRocket();
}
...
}
Now the question is, which access modifier should we add to our init() function. Should it be private or protected.
make it private <-- keeps subclasses out
make it protected <-- allows subclasses in
Before you make a choice
Now first of all, you should realize that (almost) all code in the Engine class can be replaced by a subclass.
code in a public function, can easily be overridden
code in a protected function, can easily be overridden
code in a private function, can be replaced by overriding all methods that call it.
Well, there is just one exception:
you can never modify the code of a constructor
you can never avoid a private method being called from the constructor of a super class.
(and of course, you cannot replace a final method)
Protected init() - the wrong way
Let's say the init() method is protected there is indeed a pitfall. It is tempting to override it to add features as follows. That would indeed be a mistake.
class SubEngine extends Engine {
int screws = 5;
void init() {
tightenScrews();
super.init();
}
void tightenScrews() {
// this won't print 5, but it will print 0.
System.out.println("tightening " + screws + " screws");
}
}
Protected init() - the right way
So, basically, you should just disable the parents code and postpone execution to your own constructor instead.
class SubEngine extends Engine {
int screws = 5;
public SubEngine() {
initSubEngine();
}
void init() {
// disable parent code
}
void initSubEngine() {
tightenScrews();
super.init();
}
void tightenScrews() {
// this will print 5 as expected
System.out.println("tightening " + screws + " screws");
}
}
Private init() - you may need a phonecall
Now, what if the init() method is private ?
Like mentioned above, there is no way to disable the code of a parent constructor. And if init() is private you simply cannot disable it.
You'll end up copying the entire Engine class, perhaps just to add 1 line of code.
And that may not be the end of it. Even after copying your class, your copied object won't be an Engine meaning that you won't be able to use your EngineUtil#inspectEngine(Engine engine) function.
Perhaps somebody knew this in advance and made an IEngine interface. Then you can get away with it.
In practice it means you'll have to take your phone, and call to that other department that made the Engine class, and ask them to change their code a little to take away some restrictions.
Intelligent design
There is another way. Constructors are for setting variables. They shouldn't activate anything. Everytime you see a class creating a new Thread from their constructor (or through a private method) that should be a red flag.
class Engine {
public Engine() {
}
public void init() {
lockDoors();
releasePressure();
tightenSeatbelts();
launchRocket();
}
// and you probably also want one of these
public void shutdown() { ... }
...
}
Intention
Of course, your intention may very well be not to open up your code. Perhaps you really don't want to allow others to extend your classes. There certainly can be cases where you want to lock people out.
Be aware that it will also make it harder to write tests for your code.
Anyway that's a different scenario.

Categories