Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods from a super class when a subclass is instantiated

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

like image 333
Keropee Avatar asked Nov 01 '22 00:11

Keropee


1 Answers

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.

like image 98
Chetan Kinger Avatar answered Nov 12 '22 22:11

Chetan Kinger