简体   繁体   中英

How can I override methods?

I'm trying to override the methods init() , render() and release() , but can't get it to work. I've looked at tutorials on overriding and have checked the following:

  • Overriding of methods takes place inside the subclass of the original methods
  • The method names are the exact same
  • The parameters are the same (none in this case)

I have 2 classes:

public class Game {
    public void run() {
        System.out.println("Running!");
        init();
        render();
        release();
    }

    public void init() {}

    public void render() {}

    public void release() {}
}

and

public class Loader extends Game {

    @Override
    public void init() {
        System.out.println("Initializing");
    }

    @Override
    public void render() {
        System.out.println("Rendering");
    }

    @Override
    public void release() {
        System.out.println("Releasing.");
    }

}

Why is the only thing printed to the console "Running!"?

您必须使用覆盖类 Loader 对象的 run() 方法而不是 Game 对象来获得所需的结果。

You have to override the Game#run function by creating a method in the subclass with the @Override annotation.

public class Loader extends Game {

    @Override
    public void run() {
        System.out.println("Running from Loader!");
    }

}

When you define the Game object you have to instantiate a new Loader object.

Game game = new Loader();

game.run(); // this object is an instance of Loader so Loader#run() is called. 

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