I'm somewhat new to Java and I was wondering if there was a way to change the function of a class somehow.
Class pager = new Pager();// everything is initialized
pager.dostuff() = function(){};
Is there a specific name for this and is it possible to do in Java? If not, is there a language that does allow it?
Thank you for your time.
Edit:
To clarify the question because originally it seemed like I wanted to initialize the new class with different functions. That is not the case. I want to change it after it's already been created. The reason for this is that I'm working with android and the class I'm getting is from the xml. Is it possible to change the class' function when I get the class like so?
Pager pager = (ViewPager) findViewById(R.id.pager)
I feel like I'm going to have to create a new class, which is ok but I wanted to see if I could do it this way.
In java you can override method at runtime like -
Pager pager = new Pager(){
#Override
public void dostuff(){
....
}
};
Runtime it will create subclass of Pager and override the doStuff method.
Of course ..It is possible through overriding of a class through an annonymous inner class while inheriting all the properties of the class being overriden.
Pager pager = new Pager(){
public void dostuff(){
....
}
}
PS:- Beware,Outside the anonymous inner class ,you may invoke only those methods present in your parent class through the instance of your annonymous inner class
Java does not offer a functionallity like this.
Maybe it is possible for you to override the function in a sub-class.
What you Showed above can be done in Ruby (i think).
Override
Pager pager = new Pager() {
#Override
public void doStuff() {
doSomethingElseFunct();
}
};
Related
I've been working on Xamarin for the past couple of years along with Android studio and I decided to create an application for a friend (full source code here https://github.com/nekrull/waiter don't be too harsh please :) )
The idea is that there is a base activity which exchanges fragments when a new screen should appear.
Fragments have everything that has to do with user interaction and the activity they are attached to handles the business logic.
To do this I have a base class CoreActivity/DataActivity which has some methods most Fragments use (like blocking the back button) and some helper methods (like calling a method on an attached fragment of a specific class) , a CoreInteraction that responds to this activity and
CoreFragment/AttachedFragment which is used as the base of all view fragments
so for example the view fragment would look like this:
public class GroupsFragment extends AttachedFragment<GroupsFragment.GroupsInteraction> {
//this is what we expect to be able to call in the parent
public interface GroupsInteraction extends CoreInteraction {
Group get_shown_group();
void new_group();
void select_parent();
}
}
which is basically a fragment that expects its attached activity to be able to respond to the interaction methods.
the activity fragment would look like this:
public class MainActivity extends DataActivity<MainData> implements
GroupsFragment.GroupsInteraction, (other interactions here) {
}
The problem is that since the application I'm working on has only one Activity with many small screens, the code inside the base activity will get big, that does not cause a problem with the application or compiling or anything else. But it makes it really hard to find what I'm looking for easily.
What I used to do in Xamarin is something like this:
public partial class MainActivity : DataActivity<MainData> {
}
for the initialization activity and then each interaction would get its own file like this:
public partial class MainActivity : GroupsInteraction {
}
It had the same effect (since the class is compiled as a single class) but the code would be tidy and easy to read.
Obviously there are no partial classes in Java, but is there a way to delegate the implementation of an interface to another class?
Something along the lines of saying "when you're invoking a method from interface a, invoke it from that class" without actually writing stuff like :
public Group get_shown_group() {
return new GroupHandler(this).get_shown_group();
}
public void new_group() {
new GroupHandler(this).new_group();
}
public void select_parent() {
new GroupHandler(this).select_parent();
}
Thanks in advance for any help you can provide
Something along the lines of saying "when you're invoking a method from interface a, invoke it from that class"
Taking you literally what you describe is plain delegation, a class does not implement some or any functionality itself, instead it wraps a class implementing the desired functionality, calling the methods of said wrapped class. You could even switch implementation at runtime, just changing the wrapped class as you go (assuming the classes share a common interface, of course). Of course that does not "spare" you from writing the delegations yourself.
class Wrapper implements GroupsInteraction {
private final GroupInteraction gi;
public Wrapper(GroupsInteraction gi) {
this.gi = gi;
}
Group get_shown_group() {
return this.gi.get_shown_group();
}
// ... other interface impls
}
Additionally, you should keep the GroupHandler as a member instead of creating a new Object each time, so
public Group get_shown_group() {
return new GroupHandler(this).get_shown_group();
}
becomes
public Group get_shown_group() {
return this.groupHandler.get_shown_group();
}
You can try Delegation Pattern
BaseActivity {
MyDelegateClass delegate;
void example() {
delegate.example();
}
}
P.S. both activity and delegate implements same interface
Details here
Giving the following class of my android Project :
Preview extends SurfaceView implements SurfaceHolder.Callback
and
A extends Doc
I don't really know how to ask and I know that this is not really good but I want that from Preview, I call an abstract method of Doc. In this Doc's method, I have to call a method of the previous Object of Preview.
This is an example :
From Preview.java :
Doc _doc = new A();
private void myMethod() {
this._doc.process(this)
}
From A.java :
#Override
public void process(Preview p) {
p.processA();
}
The problem is that I got an error :
The method process(Preview) in the type Doc is not applicable for the arguments (new Camera.PreviewCallback(){})
However, I can't change this judging by the fact that I want to call the method from Preview. I tried many thing such as cast etc. None of them works.
Thanks for your help !
PS : I am on Eclipse under Windows.
Assuming you are calling A.process(this) from an anonymous inner class (of type Camera.PreviewCallback I presume, hence the error message), you have to write A.process(Preview.this), since a standalone this refers to the inner class and not to the Preview instance.
The method process(Preview) in the type Doc is not applicable for the arguments (new Camera.PreviewCallback(){})
It simply means you are passing the object of Camera.PreviewCallback but in your method public void process(Preview p) You want an object of Preview.
If you have written this code in side an anonymous class, then this won't point to the Preview class. It will point to the object of inner anonymous class.
Thus you need to write A.process(Preview.this)
I am trying to include EventBus in my application.
I followed http://tomaszdziurko.pl/2012/01/google-guava-eventbus-easy-elegant-publisher-subscriber-cases/ link.
I am getting compile errors:
I've added the guava-16.0.1.jar to the project.
But the register fucntion isn't working.
Any idea what am I missing here?
You're trying to call methods on members from the class, which is not possible. Those need to go inside a method (like a constructor or initializer).
Example code:
public class EventBusTest {
private final EventBus eventBus = new EventBus("test");
private final MultipleListener multiListener = new MultipleListener();
public void init() {
eventBus.register(multiListener);
}
}
Also, this question may be of use to help you understand Classes vs Objects
I have to maintain a code to add more flexibility to a final static variable in a class.
The variable is no more a global constant and may be changed.
The problem is that the class is in a common library and used in different projects.
Do you have an approach or a design pattern better than copying and pasting the class code from the common library to my specific application and refactoring it?
Example:
Commons project
Class CommonClass {
public final static var globalSomething = somethingGlobal;
public static method(){ //CommonClass.globalSomething is used here}
}
In my App (and other apps that reference commons) we can use the static attribute and also call the method:
---> var b = CommonClass.somethingGlobal;
---> var c = CommonClass.method() //we know that CommonClass.globalSomething is used here
Expectations:
Ability to change CommonClass.somethingGlobal in my app and take these changes in call CommonClass.method()
I can modify (add methods) in the common class but i have to keep the same initial behavior (not to break other project referencing common project)
If I got you right, you want to implement this as a parameter.
Looking at your example:
var c = CommonClass.method() //we know that CommonClass.globalSomething is used here
there is already something wrong with it. You shouldn't have to know that you have to set CommonClass.somethingGlobal correctly before calling the method. This way the client has to know the implementation, violating the principle of information hiding. If the value is required, introduce it as parameter:
Class CommonClass {
public static void method(var globalSomething){}
}
An alternative would be making both your variable and your method non-static and use a constructor:
Class CommonClass {
public var globalSomething = somethingGlobal;
public CommonClass(var globalSomething) {
this.globalSomething = globalSomething;
}
public void method(){}
}
PS: Your example code is not java. I corrected it partially in my answer.
NEWBIE ALERT!
Here's the situation. I've got an Android ListActivity class (AppWindow) that contains all the methods that create and update the UI for my application. It includes a method (refreshWindow) that calls setListAdapter, and therefore must be non-static. So far, I've been using a separate class (FileHandler) to perform manipulations on files that are referenced by the AppWindow class. I've reached a point where I want to call the refreshWindow method when a certain file manipulation has been performed. However, since the refreshWindow method is non-static, it seems that I would need to instantiate AppWindow and call the method through that instance. However, I'm not sure how to do this or if it's even a good idea. Perhaps I just need to move all of the FileHandler logic into AppWindow, although I'd prefer to keep them separate.
Here's a description of the situation in code form:
AppWindow.java
...
public class AppWindow extends ListActivity {
...
void refreshWindow() {
...
setListAdapter(new ListAdapter());
...
}
...
}
FileHandler.java
...
class FileHandler extends Activity {
...
static void doStuffToFiles() {
...
AppWindow appWindow = new AppWindow();
appWindow.refreshWindow();
...
}
...
}
Should I be doing this? If so, how do I properly instantiate AppWindow?
Create a static member variable; say act; in FileHandler
On creation of ListActivity set the variable act using 'this' variable of activity
Now you can access activity instance from FileHandler.
Update the UI must be in the UI thread. You can use handler to handle the message. The handler's constructor can contain the activity, so you can use it.