简体   繁体   English

在LibGDX中使用抽象屏幕

[英]Using abstract screen in LibGDX

I want to use an abstract screen for my LigGDX game. 我想为LigGDX游戏使用抽象屏幕。 I have read many websites and many of them use abstract screen only to group the common codes (eg common methods) together. 我已经阅读了许多网站,其中许多网站仅使用摘要屏幕将通用代码(例如通用方法)分组在一起。 If this is the case, we can simply use a normal class to do the task. 如果是这种情况,我们可以简单地使用一个普通的类来完成任务。

The original purpose of abstract screen should be as follows: 抽象屏幕的原始用途应如下:

When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. 当抽象类被子类化时,该子类通常为其父类中的所有抽象方法提供实现。 However, if it does not, then the subclass must also be declared abstract. 但是,如果没有,则子类也必须声明为抽象。

Can someone explain this situtation. 有人可以解释这种情况。

Thanks 谢谢

Abstraction allows you to have many classes that share some functionality but may differ in the implementation. 抽象使您可以拥有许多共享某些功能但实现可能不同的类。 You can then declare something to be the abstract class and leave the implementation up to the subclasses. 然后,您可以声明某些东西作为抽象类,并将实现留给子类。

For example, maybe your program has a cat, a dog, a rat, and a spider. 例如,您的程序可能有一只猫,一只狗,一只老鼠和一只蜘蛛。 Well, all four of these are animals and they all share some functionality even though they're quite different in the specifics. 好吧,所有这四个都是动物,尽管它们在细节上完全不同,但它们都共享一些功能。 Cats, dogs, rats, and spiders all move and they all eat but they do so very differently. 猫,狗,大鼠和蜘蛛都会移动,它们都吃东西,但是它们的饮食方式却大不相同。 You might declare an Animal abstract class and then a Spider class, a Cat class, a Dog class, and finally a Rat class all extending Animal. 您可以先声明一个Animal抽象类,然后再定义一个Spider类,一个Cat类,一个Dog类,最后是一个Rat类,它们都扩展了Animal。

public abstract class Animal {
    int numLegs;
    float speed; // in meters per second
    int weight;

    abstract void walk();

    abstract void eat(Object food);
}

public class Cat extends Animal {
    public Cat() {
        numLegs = 4; // cats generally have 4 legs
        weight = 10; // 10 pounds
        speed = 13; // cat can run 13 meters per second
    }

    public void walk() {
        // TODO: implement walking functionality for cat
    }

    public void eat(Object food) {
        // TODO: implement check to make sure food isn't poisonous
        // TODO: make cat eat food
    }
}

// Similarly for other animals

public class MyProgram {
    public void myWorld() {
        List<Animal> animals = new ArrayList<Animal>();
        animals.add(new Cat());
        animals.add(new Spider());

        for (Animal a : animals) {
           a.move();
        }
    }
}

Check out this documentation for more details. 查看文档以了解更多详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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