Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use abstract class as type

So while trying to understand abstract classes, there is still one thing I am confused on. When do you ever want to declare an object type of its abstract class. For example

public abstract class GameObject
{
 public abstract void draw();
 public static void main(String[] args)
 {
 GameObject player = new Player();
 Menu menu = new Menu();
 }

}
public class Player extends GameObject
{
 override 
 public void draw()
 {
 // Something
 }

}
public class Menu extends GameObject
{
 override 
 public void draw()
 {
 // Something
 }
}

Normally, I would just instaniate a player object of player type. However, I have seen abstract classes used as the variable type of the new object. When would you ever choose to do this? Thanks!

like image 727
john woolstock Avatar asked Oct 17 '25 14:10

john woolstock


1 Answers

You would do that every time you need the variable to be an instance of the abstract class, but don't really care about what the concrete type is (and don't want the rest of the code to assume a specific subclass is used). For example:

GameObject[] gameObjects = new GameObject[] {new Menu(), new Player()};
drawAll(gameObjects);

...

private void drawAll(GameObject[] gameObjects) {
    for (GameObject gameObject : gameObjects) {
        gameObject.draw();
    }
}

The abstract type is often used as a return type (because you don't want the caller to know what concrete type is returned: it could change later, or could vary based on the arguments of the configuration).

It's also often used as method parameter type, so that the method can accept an argument of any subclass of the abstract type and use it polymorphically.

And of course, as an array/collection type, to be able to store instances of multiple subclasses in a unique collection.

like image 100
JB Nizet Avatar answered Oct 20 '25 04:10

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!