简体   繁体   中英

How can I call an Inherited function to execute when declared in child class

Take this sample code from Unity 3D

public class Enemy : MonoBehaviour 
{
    void Start()
    {

    }

    void Update()
    {
       transform.postion = Vector3.Lerp(transform.position, new Vector3(0, 1, 0), 5f * Time.deltaTime);
    }
}

As you can see, the class Enemy inherits from MonoBehavior which contains the Start and the Update methods. All I have to do is put in my own code there, but, I would like to know how to create a similar thing say for building a Chat API in Java for instance, where I would lay it out to the consumers to just access my base class and would have a function like "Update" that was executed every second without them having to manually code a while loop.

How can I create a base class function that can be called automatically when the child class declares it? I am open to any programming language anyone could answer it with, all i want to know is the logic behind this.

The base class could have a timer created in it's constructor that is setup to call an abstract method on a 1s interval.

public abstract class BaseClass
{
    private Timer _timer;

    protected BaseClass()
    {
        _timer = new Timer();
        _timer.Tick += (sender, args) => 
       {
          Console.WriteLine("Calling Update."); 
          Update();
       };
        _timer.Interval = 1000;
        _timer.Start();            
    }

    protected abstract void Update();
}

public class InheritedClass : BaseClass
{
    protected override void Update()
    {
        Console.WriteLine("Update was called.");
    }
}

You can use this in a console app to demo the functionality.

public class Program
{
    public static void Main(string[] args)
    {
        var inheritedClass = new InheritedClass();
        Console.ReadLine();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM