Using abstract screen in LibGDX

759 views Asked by At

I want to use an abstract screen for my LigGDX game. I have read many websites and many of them use abstract screen only to group the common codes (e.g. 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

1

There are 1 answers

5
David M On BEST ANSWER

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.

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.