How would you create a Class that whichever class extends the Class, methods are automatically invoked/called. Just edit my question if it sounds misleading. I'll just showcase some samples
Example 1:
In unity when you extend monobehavior your methods are automatically called. I don't know if I'm right.
public class MyController : MonoBehaviour {
void Start()
{
//Being Called Once
}
void FixedUpdate()
{
//Being Called every update
}
on libgdx
Game implements ApplicationListener {
#Override
public void render () {
//Called multiple times
}
}
As What I have Understand and Tried Implementing it my self
public abstract Test{
protected Test(){
onStart();
}
public abstract void onStart();
}
public class Test2 extends Test{
public Test2(){
}
#Override
public void onStart(){
//Handle things here
}
}
I'm sorry, but I still really don't know how it works or what you call this technique.
Especially in unity, when creating multiple controllers that extends Monobehavior, all that controllers method that been implemented are called. Who's calling this classes and methods? Some reference or books on this would be a great help.
Note: Please edit my title for the right term to use on this. thanks
I'm sorry, but I still really don't know how it works or what do you call this technique
In your Java example, the onStart method is said to be a hook or a callback method.
Wikipedia defines hooking as follows :
In computer programming, the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a "hook"
Wikipedia defines a callback as follows :
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback, or it might happen at later time as in an asynchronous callback
Any class that instantiates Test method from the Test class will result in the onStart method of the instance being called. Example :
Test test = new Test2();//calls onStart in Test2.
That being said, I am not sure who calls the methods in case of MonoiBehavior but your general understanding of how to implement a hook or a callback in Java is correct.
Related
It seems that an abstract class means the definition of the class is not complete and hence cannot be instantiated.
And I saw some simple Java code which has an abstract class with all of the methods defined. Then I was wondering, why do they make it as an abstract class instead of a real class? Are they doing this so we cannot instantiate from this abstract class? Or they are getting other benefits from making an abstract class with everything defined?
It is possible that even though all the methods had a default implementations, these implementations weren't actually meaningful in the context of the application. The methods might only do internal bookkeeping while the actually useful implementation must be provided by a derived class which does what it needs to do and then calls the superclass method.
However, this is just speculation. You would have to show an actual example to tell what could be the reason for this design.
As an example, let's take a simple game engine. I have lot's of different GameObjects in my game.
Some are visible, so my basic class gets a draw() method. But there might be invisible objects like trigger areas which don't show up at all, so I implement it as a no-op in the base class.
Some do something when they collide with something, so each one gets a collide(other) method. But some don't do anything when they collide like a purely visual particle effect, so I also provide a no-op in the base class.
Some do something every game tick, so they get a update() method. But some objects, like a wall, might not do anything at all on their own. So I also provide a no-op for this.
So what do I do when I have an object which is invisible, doesn't do anything on its own and doesn't interact with anything? There is no reason to have this in the game. So I make this basic class abstract. Theoretically you could instance it because all methods have an implementation, but practically you have no reason to ever do this, and when you try, you misunderstood how my game engine works.
One typical use case is the creation of an adapter class. Think of a callback interface where you could be notified of 10 different events but are normally only interested in some of them. With an adapter class, you can provide empty implementations such that an actual callback only needs to implement those methods that are of interest after extending the adapter. By making the adapter abstract, you express the fact that it makes no sense to instantiate the adapter itself as it does nothing useful.
Since Java 8, you would not longer implement such an adapter but use default methods for the interface.
Yes, there is. Sometimes you know you're creating an abstract class - one that will have to be derived from to make any actual sense, but you want to provide a default implementation to all the methods. This doesn't happen a lot, but it does happen.
UPDATE:
I just had a case like this. I'm recording various user generated events. Each event has a TimeSpan and a Description, and they all have other things as well. I've created a base event class:
public abstract class BaseEvent
{
public TimeSpan EventTime {get; private set;}
public string Description {get; protected set;}
public BaseEvent(TimeSpan time, string desc) ...
}
Granted, this is C# and not Java, but had I written this in Java, I would have done exactly the same thing)
You can have an abstract class that implements several interfaces. You need not implement these methods in an abstract class, but you do need to implement them in a subclass of your abstract class.
E.g.
public interface MyInterface{
void hello();
}
public abstract class Clazzy implements MyInterface {
//I need not have the interface method.
}
public class MySubclass extends Clazzy {
#Override
public void hello() {
// I need to be here
}
}
If a Java class is declared abstract yet has all of its methods declared, then they are doing it so it cannot be instantiated, though it may be subclassed.
"Abstract classes cannot be instantiated, but they can be subclassed."
See here: https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
You might have some classes that don't make sense in the context of your application but they do in the design.
A silly example:
Abstract class animal, implement born and die. You don't want an "animal". You want a Dog.
This way you don't have to repeat the code each class you add. Now you can have Dog, Cat or whatever you want, this would be a good reason, anyway it's hard to find.
I see this question is already marked answered, but I'd like to provide another alternative explanation.
Another reason for this kind of code would be to provide a base implementation for all derived classes of that abstract class.
Then when implementing new derived classes you have a runable implementation that you can then choose to override the methods of in order to customize behavior for that derived instance.
Take the case of an BaseItemBuilder which is abstract and provides data access logic based on a common argument, such as ItemNumber.
(Sorry for the C# code but this question is pretty much just programming theory more than it's about a specific language)
public abstract class BaseItemBuilder { /*I don't want anyone using this directly but I do want the base specification*/
public virtual void GetInfoAboutItem(int itemNumber){
var infoModel = _infoDataService.GetItemInfo(itemNumber);
//project values on to internal representation of item
}
public virtual void GetMoreInfoAboutItem(int itemNumber){
var infoModel = _infoDataService.GetMoreItemInfo(itemNumber);
//project values on to internal representation of item
}
public virtual void GetEvenMoreInfoAboutItem(int itemNumber){
var infoModel = _infoDataService.GetEvenMoreItemInfo(itemNumber);
//project values on to internal representation of item
}
public virtual void GetYetMoreInfoAboutItem(int itemNumber){
var infoModel = _infoDataService.GetYetMoreItemInfo(itemNumber);
//project values on to internal representation of item
}
}
You could then derive a NormalItemBuilder which uses the base implementation. This accounts for 80% of the items that you are tracking.
public class BaseItemBuilder {
/*I use the base implementation!*/
}
Then you derive a SpecialType1ItemBuilder that goes to a couple of different data services to acquire information about that particular item type, but still uses some of the base implementation defaults. This covers the next 10%.
public class SpecialType1ItemBuilder { /*I don't want anyone using this directly but I do want the base specification*/
public override void GetInfoAboutItem(int itemNumber){
var infoModel = _infoDataService.GetType1ItemInfo(itemNumber);
//project values on to internal representation of item
}
public override void GetYetMoreInfoAboutItem(int itemNumber){
var infoModel = _infoDataService.GetYetMoreType1ItemInfo(itemNumber);
//project values on to internal representation of item
}
}
Then you derive a `SpecialType2ItemBuilder' that goes to yet another set of sporadic dataservices to complete a picture of that item. This one goes overrides another set of methods that are different from Type2ItemBuilder. This covers your last 10%.
public class SpecialType2ItemBuilder { /*I don't want anyone using this directly but I do want the base specification*/
public override void GetInfoAboutItem(int itemNumber){
var infoModel = _infoDataService.GetType2ItemInfo(itemNumber);
//project values on to internal representation of item
}
public override void GetMoreInfoAboutItem(int itemNumber){
var infoModel = _infoDataService.GetMoreType2ItemInfo(itemNumber);
//project values on to internal representation of item
}
}
I know this question has been asked before. But I want to understand the difference with the perspective of my code.
So here is the scenario.
I have a class Main.java. This class calls a different class Secondary.java . On a particular method in the Secondary class, I want some values in the Main class to be updated. There are two ways to do this.
1) One way for doing this is through Callback functions in java.
2) Second is if I define a static function in Main class, then call the static function from Secondary Class.
Here are my two approaches.
Approach 1
Interface CallBack.java
public Interface Callback{
public void updateValues();
}
Main.java
public class Main implements Callback {
static int a=1;
public static void main(String args[]) {
Callback callback = new Main();
Secondary obj = new Secondary(callback);
obj.onClick();
}
public void updateValues(){
a = 4;
}
}
Secondary.java
public class Secondary{
private Callback callback;
Secondary (Callback callback) {
this.callback=callback;
}
//On this method click, I want to update values in the Main class
public void onClick(){
callback.updateValues();
}
}
Approach 2
public class Main {
static int a=1;
public static void main(String args[]) {
Second obj = new Second();
obj.onClick();
}
public static void updateValues(){
a = 4;
}
}
public class Secondary{
Secondary () {
//On this method click, I want to update values in the Main class
public void onClick(){
Main.updateValues();
}
}
So I just want to know that which approach is better? When are callback functions really useful?
Note: This is just an example to understand the difference between the two concepts.
Which approach is better? The answer always depends on context, there are cases to break every rule. That said, keeping coupling low and code simple and unit tested are the usual priorities.
static method
pros: simple, and direct
disadvantages: the static method cannot be substituted with
other implementations.
callback approach
pros: easy to substitute callbacks, good for mocking in tests
cons: a little more overhead for the callback (although JVMs
can often optimise them out) and a little more conceptual
cost to developers; which will be low if they are not abused.
Judging by your choice of example, I suspect that you are working on a GUI. With large applications, the static method approach does not tend to scale without becoming brittle to change. So while your application is small, you will find that the static method approach is simple and tempting. However as your application grows, and you add more people to the project who all need to make changes to the growing code base at the same time we need ways to isolate parts of the application and to unit test those parts. This is where the callback approach shines.
The danger with the callback approach is that it becomes over used. Avoid nesting callbacks as much as possible (there are patterns from the functional world that make this a great technique, but perhaps that is for another post) and the callback must not know about the caller. A cyclic dependency tends to complicate code at a non-linear rate.
I would personally prefer Approach 2 from what you described. That leaves me with principle called open for extension and closed for modification.
So tomorrow if i have a new Callback i could inject it directly in it and use updateValue method.
If i have ever to follow the approach one then this means:
I am breaking OOP principle by using static. You would not be able to override static method.
If tomorrow your updateValue needs change you are going to change Main which breaks closed for modification principle
This would close the doors of further reusability as well.
I have a class A extending class B .
My class B has 5 abstract methods. In all these 5 methods , I need to make one call each to a methodA() . The problem with this is that since I need to create around lets say 40 classes which extend classB , I need to write same calls for methodA , 5 times per class and in all those 40 classes.
SO I end up writing calls to methodA , around 200 times.
Now how can I design this such that I don't need to make these calls at child class level?
Example below
The methodA here is a method which logs User's action in the database.
So each time I create a class extending class B, in all the 5 abstract methods I need to call a methodA which logs user's action in database.
Thanks
You can use a pattern like this:
abstract public class B {
/** Override to implement the subclass logic */
abstract protected SomeClass reallyCalculateStuff();
/** The public API method to be called by clients of the class */
final public SomeClass calculateStuff() {
executeSharedCode();
return reallyCalculateStuff();
}
/** The method all other methods need to call */
private void executeSharedCode() {
// ...
}
}
public class A extends B {
#Override
protected SomeClass reallyCalculateStuff() {
// ...
}
}
You obviously would want to come up with better names. But the idea is that the base class already contains the public API and takes care of calling the shared method.
This will also work if executeSharedCode needs to be implemented differently in every subclass. Just make it abstract as well.
However, depending on the usecase, there might be better alternatives to this. For example, interceptors. It might also be worth to rethink the design as this pattern could be perhaps avoided by designing classes differently. But all those things are impossible to judge without context, so I'll just give you this pattern.
If you want to reduce code copying, you can make the methods in B non-abstract and give them method bodies. This will mean that they aren't abstract any more, but since all subclasses will inherit this behavior you can still rest assured they will all be able to use the method. Thus, the methods in B can call methodA(), even if methodA is defined in the subclasses, and they can also be overridden by your subclasses if they need unique behavior.
Unfortunately, there's no way to intrinsically call the body of the parent class' method. You'll need to be a bit explicit about it using super.
Your parent class:
public class B {
public methodA() {}
public firstMethod() {
methodA();
}
}
Your implementation:
public class A extends B {
public firstMethod() {
super.firstMethod();
// method body
}
}
So, you still have to call super.firstMethod in your implementation, but at least this way, you can have a more extensive default implementation than a single method call.
So I have been reading a tutorial on Android development, and I have come across something that I have never seen during my Java developing (mainly school work):
Thread th = new Thread() {
public void run() {
if (iotdHandler == null) {
iotdHandler = new IotdHandler();
}
iotdHandler.processFeed(); resetDisplay(
iotdHandler.getTitle(),
iotdHandler.getDate(),
iotdHandler.getUrl(),
iotdHandler.getDescription());
dialog.dismiss();
}
};
th.start();
Now the book says extend thread, and I kind of understand what its doing, in a sense, but it doesn't follow the usual way to extend a normal class in java like so:
public Class Dog extends Animal...
and then you can follow on and override methods and such. But my question is, what is it actually doing in making a reference to new Thread object, but at the same time creating a method right after it, and what I assume is overriding some sort of method in the Thread class? Since I do not know what it is called, I can't really search for it, so I apologize for the obvious question if it is one. Any help would be much appreciated.
Revise your Java books :) It's called an anonymous inner class and was originally introduced to facilitate Java GUI development (with AWT/Swing). Since Android UI development follows many of the same patterns, it is used quite often in Android.
What it does is instantiating a class in place (without defining it in a separate file, etc.), overriding some of its methods (int this case run()). You can also implement an interface this by if you provide implementations for all of its methods.
first of all, that is nothing Android specific. You can extend the same way in "normal Java". The reason for doing an class extend like that is to reduce classes, when this "class extension" is needed only once. In your example it would be the same to write
public class MyThread extends Thread
{
#Override
public void run() {
[...]
}
};
and later on:
MyThread thread = new MyThread();
thread.start();
So the advantage is, that you don't need to implement a class and instantiate it later on.
I have event observers which all observe the same event, so I have an abstract superclass which observes that event and then the subclass overrides / implements the specific functionality.
The problem with this is that it doesn't observe the event unless I put the event observer method in the subclass (which defeats the purpose of my design).
I can most certainly do it this way, but I want to write as little code as possible.
Should it work this way (am I doing something else wrong)?
If it isn't supposed to work this way, then I can write a producer for one thing and then an interceptor. I thought that my first approach was simpler and more likely to be used properly by other developers.
example code:
SuperClass:
public abstract class AbstractFileWriter
{
public void onReady(#Observes ReadyEvent readyEvent)
{
try
{
handleReady(readyEvent, ...);
}
}
protected abstract handleReady(ReadyEvent readyEvent, otherParameters go here);
}
SubClass
public class XmlWriter extends AbstractFileWriter
{
protected handleReady( ... )
{ ... }
}
If I write it this way, handleReady is never invoked (and neither is onReady for that matter); however, if I write it with the observer method within the subclass, it works as expected. I want to write it this way as there is much less code I'd have to write and a little bit less abstraction which should make it easier to understand.
Walter
Either declare the relevant method in the superclass to be abstract or have it call an abstract "detail" method that each subclass implements.
I wrote a decorator as I mentioned above. This essentially does the same thing, just written slightly differently.
Walter