Calling instance method in Java - java

Following this tutorial:
http://developer.android.com/training/notepad/notepad-ex2.html
In Step 2, this method gets called:
registerForContextMenu(getListView());
which is a public method of Activity. Now, I'm a bit of a Java newbie here - I thought if you wanted to call an instance method of a superclass you needed to preface it with this. E.g.
this.registerForContextMenu(getListView());
Is it just a style thing here? Is there any difference between
this.registerForContextMenu
and simply
registerForContextMenu

No, there is no difference.
You don't have to use this., but it is often done anyway to make the code clearer.
For one thing, it makes it easy to tell if a method is static or not if you use the convention of calling instance methods like this:
this.registerForContextMenu() 
and static methods like this:
ClassName.staticRegisterForContextMenu()

you do not have to use this. If you ommit it it is assumed you called method in this scope. One particular example when this may help could be i.e.:
Boolean someVar;
public function setMe( Boolean someVar ) {
this.someVar = someVar;
}
In this case, w/o this you would get the error.

To call a method of superclass either you need object of superclss or keyword super .
eg.
superObject.superclassMethod();
super.superclassMethod();
this is a reference of the current object. this can be used to call method of a class in which it is used. this can never be used to call a superclass method.
As for
this.registerForContextMenu()
and
registerForContextMenu()
no such difference. you can use either of them.

Both ways are correct for calling a method on the current (this) instance of the class. Non private methods are inherited from super classes, so you can use the same syntax to call such methods.

Related

Difference between 'level.tick()' and 'Level.tick(level)'

I'm a Java devloper in my spare time and i just was wondering what would be the difference between
level.tick()
and
Level.tick(level)
('Level' being the name of the class and 'level' being an object of that class)
I know that since java works by referencing objects, that calling the static function from the class passing the level as parameters would surely have the same effect as 'level.tick()'
(Please note this is not for a project I'm working on, I just thought I'd ask)
)
Both can implement the same functionality. Most commonly you use the first instance method declaration. However, if level can be null, then you would need to add a checking before that call. The second static method declaration can include this checking and reduce the boilerplate you have to write.
public class Level {
public void tick();
public static void tick(Level level);
}
level.tick(); // Safe to call if level can't be null
Level.tick(level); // Safe to call in any case
Designing the application so that variable values are never or only in exceptional cases are null can save you from a lot of headache.
The first method will call the non static function of Level class which is accepting no arguments.
The second method will call the static function of Level class which is expecting an argument of type Level.
If I understand correctly,
I know that since java works by referencing objects, that calling the static function from the class passing the level as parameters would surely have the same effect as 'level.tick()'
Level.tick(level)
does NOT automatically translate to
level.tick()
This would only work if you had a static function which had the 2nd form as the body.

java explicitly call super method

Are there any reason to call method from super class?
I have met lots of places where super method called instead of this method, e.g.:
public String getCustomValue() {
String value = (String) super.getValue(someArgHere);
return value;
}
Any benefits? I just see one major problem with inheritance: if I override getValue in this class or in one of its descendants getCustomValue will neglect that override and call super method.
super.getValue(someArgHere) calls the getValue method of the super class. In contrast, this.getValue(someArgHere) calls the getValue method of the current class, if defined. If the current class does not override getValue, the super class method is called.
Unless you overwrote the method getValue(...) and you are really sure (your sureness deserves a comment in the code) you want to bypass it you should not use super like you are doing. Later on if you or someone else decide to overwrite getValue(...) they probably wanted the effect to apply to getCustomValue() as well.
Although you definitely can call super.myMethodOne() from myMethodTwo(), the usual scenario is when you want to call super.myMethodOne() from myMethodOne() when you override it. Some languages like Ruby even pass up the method arguments automatically for you so that you don't have to retype them.
Here is one example:
public class A {
public void close() {
// do a bunch of things...
}
}
public class B extends A {
#Override
public void close() {
// close things related to the subclass B
// and then make sure A is closed as usual...
super.close();
}
}
There are no technical advantages of using super over this in the case where the method is not overridden.
However, one might say that it's clearer to use super instead of this for the reason you've just mentioned. If you override the function in your subclass, then you will need to use super; if you don't you can use this. Instead of playing guessing games (or forcing people to check whether the method has been overridden), you can just always use super when you mean super.
I just see one major problem with inheritance: if I override getValue in this class or in one of its descendants getCustomValue will neglect that override and call super method.
Then don't call the super method explicitly, just call getValue. If the method has not been overriden it will default to the super-method. If it has, it will use the overriden method.
I don't know if it's appropriate to ask about "benefits" in this case - it really just depends on what exactly you are trying to accomplish.
The thing is the design. When we code, we do it as per what it is!
So even if getValue is extended, its perfect, because that is what your class is suppose to do.
Normally, super is used, to obtain any information or data or side effect from the super type and modify or improve it as per your current class functionality
The only benefit is if your class overrides the method of the superclass you still can call the method of the superclass using super.

Is calling static methods via an object "bad form"? Why?

In a recent question, someone asked about static methods and one of the answers stated that you generally call them with something like:
MyClassName.myStaticMethod();
The comments on that also stated that you could also call it via an object with:
MyClassName myVar;
myVar.myStaticMethod();
but that it was considered bad form.
Now it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not (a).
Is there some problem with calling static functions via an object? Obviously you wouldn't want to create a brand new object just to call it:
Integer xyzzy;
int plugh = xyzzy.parseInt ("42", 10);
But, if you already have an object of the desired type, is there a problem in using it?
(a) Obviously, I can't call a non-static method with:
MyClassName.myNonStaticMethod();
but that's not the issue I'm asking about here.
In my opinion, the real use case that makes this so unreadable is something like this. What does the code below print?
//in a main method somewhere
Super instance = new Sub();
instance.method();
//...
public class Super {
public static void method() {
System.out.println("Super");
}
}
public class Sub extends Super {
public static void method() {
System.out.println("Sub");
}
}
The answer is that it prints "Super", because static methods are not virtual. Even though instance is-a Sub, the compiler can only go on the type of the variable which is Super. However, by calling the method via instance rather than Super, you are subtly implying that it will be virtual.
In fact, a developer reading the instance.method() would have to look at the declaration of the method (its signature) to know which method it actually being called. You mention
it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not
But in the case above context is actually very important!
I can fairly confidently say it was a mistake for the language designers to allow this in the first place. Stay away.
The bad form comment comes from the Coding Conventions for Java
See http://www.oracle.com/technetwork/java/codeconventions-137265.html#587
The reason for it, if you think about it, is that the method, being static, does not belong to any particular object. Because it belongs to the class, why would you want to elevate a particular object to such a special status that it appears to own a method?
In your particular example, you can use an existing integer through which to call parseInt (that is, it is legal in Java) but that puts the reader's focus on that particular integer object. It can be confusing to readers, and therefore the guidance is to avoid this style.
Regarding this making life easier for you the programmer, turn it around and ask what makes life easier on the reader? There are two kinds of methods: instance and static. When you see a the expression C.m and you know C is a class, you know m must be a static method. When you see x.m (where x is an instance) you can't tell, but it looks like an instance method and so most everyone reserves this syntax for instance methods only.
It's a matter of communication. Calling a method on an instance implies you're acting on/with that particular instance, not on/with the instance's class.
It might get super confusing when you have an object that inherits from another object, overriding its static method. Especially if you're referring to the object as a type of its ancestor class. It wouldn't be obvious as to which method you're running.

Invoking dynamic Method without known Constructor?

If I do this in Java to call a method name from a class dynamically, it works.
MainApp app = new MainApp();
Method meth = app.getClass().getMethod("myMethod", MyParameterType.class);
//call method
meth.invoke(app, new MyParameterType("hello"));
But this worked because I know the constructor in the invoke method. But if I were to pass the Method object as a parameter to some other classes, and I don't know who is the constructor, I cannot invoke the method any more. Even if I know, I may not want to create a different object to just make a call to the method. For eg:
//This is in the class call MainApp.java.
//There is a method in MainApp.java that looks this way: myMethod(MyParameterType param);
MainApp app = new MainApp();
OtherClass myClass = new OtherClass();
Method meth = app.getClass().getMethod("myMethod", MyParameterType.class);
myClass.callMe(meth);
//Inside OtherClass.java
public void callMe(Method meth) {
//call method
meth.invoke(########, new MyParameterType("hello"));
}
In this case, what should I put for the ######## parameter? Within the context of OtherClass.java, the base constructor object wouldn't be known. And why would I need if since meth is already a Method type that I just call like a function?
Thanks
Assuming it's an instance method, you've got to have an instance to call the method on, just like anything else. How you get hold of that instance will depend on what you're trying to do; you could pass in a Constructor, or a reference to an existing object, or some interface which will create the instance when you ask it to... we can't really give you any advice on which approach is the most suitable without knowing what you're trying to do.
If it's a static method, you can pass null for the first argument.
What it seems you are looking for or thinking about is the concept of `lambda functions``. Those can be called in isolation.
A Method type is not a standalone method, but more like a 'path' into an object. Compare this with a relative URL like /subscribe.html. Out of context this is pretty useless, but when bundled with a site like www.example.com it makes sense.
As such, Method can only be used in combination with an instance. (edit: as John mentioned, unless it's a static method of course which do not need instances)
If you can safely invoke a method without providing an instance, it should be a static method, in which case any instance provided is ignored, you can give it null.
If you have to provide an instance of the object, there is no way around this.
If the developer who write the method has labelled it non-static incorrectly, I suggest you discuss with them why they did it.

Why is accessing a static method from a non-static method bad?

Netbeans tells me it's bad to access a static method from a non static method. Why is this bad?
"Accessing static method getInstance" is the warning:
import java.util.Calendar;
public class Clock
{
// Instance fields
private Calendar time;
/**
* Constructor. Starts the clock at the current operating system time
*/
public Clock()
{
System.out.println(getSystemTime());
}
private String getSystemTime()
{
return this.time.getInstance().get(Calendar.HOUR)+":"+
this.time.getInstance().get(Calendar.MINUTE);
}
}
You're probably accessing the static method from an instance instead of directly. Try using Calendar.getInstance() instead:
private String getSystemTime()
{
return Calendar.getInstance().get(Calendar.HOUR)+":"+
Calendar.getInstance().get(Calendar.MINUTE);
}
What do you mean by "return a static method"? It's fine to call a static method from an instance method in my view - depending on the circumstances, of course. Could you post some code which Netbeans complains about?
One thing I could imagine is if you only use static methods from an instance method, without using any of the data of the instance. Sometimes that's what's required to implement an interface or override a method from a base class, but if you're not overriding anything and you're not using any instance variables, it's nice to make the method static to show that it really doesn't depend on a particular instance.
EDIT: With the edited question, this makes a lot of sense. IMO it's a deficiency in Java that allows it in the first place. It can make for very misleading code. My favourite example (which means old-timers may well have seen me post it before :) is with Thread.sleep. What does it look like this code does?
Thread t = new Thread(someRunnable);
t.start();
t.sleep(1000);
To my mind, it looks like the new thread is asked to sleep - similar to a call to suspend. But no - you can only ask the currently executing thread to sleep, which is why Thread.sleep is a static method. The above code is legal Java, and will make the currently executing thread sleep for a second while the newly created thread (probably) runs... not at all what the code looks like at first glance.
Do you have the order reversed? If so, it makes sense that you cannot access a non-static method from a static method. If not, I'd like to know why this is bad as well!
A non-static method can not be referenced from a static context. Static methods can be referenced from a non-static context.
Is it a Netbeans error or warning ? Can you post code that is causing it ?
It's just fine to call time.getInstance(). The compiler will look at the type of the variable, Calendar in this case, and call the method there. It ends up being compiled exactly as Calendar.getInstance(). Note that the actual value of time does not contribute to this, i.e. it can even be null and it doesn't matter.
It's this indirection and difference from regular methods that is frowned upon. It's best to express it directly as Calendar.getInstance().
why just not explain simple:
if you call nonstatic method,
1) you create new instance with a=new Class();
2) then call method a.method;
if you call static method:
1) you call it Class.method;
You can do it with static method just because it is independent within its class and have all it needs for calling. If it depends on some other info (as constructor) you dont declare it static, it will fail.
In java all static member variables will be loaded into memory first,
then all static members will be loaded,
after that non-static variables and member functions will be loaded into memory,
after that static main block will be executed.......
so it was giving the error that a non..............

Categories