简体   繁体   中英

Making an superclass with methods in it

I am wondering if I can make my piece of work smarter . I have 2 classes:

Enemy class(the superclass of any enemy):

package com.joetannoury.game.entity.enemy;

/**
 * Enemy's superclass!
 *
 * @author Joe Tannoury
 */
public abstract class Enemy {

    public Enemy(int EnemyID, float x, float y) {

    }

    public abstract void update(int delta);
    public abstract void render();
}

An enemy class(a subclass of enemy):

package com.joetannoury.game.entity.enemy;

import java.util.ArrayList;

/**
 * This is an subclass of Enemy!
 *
 * @author Joe Tannoury
 */
public class E0 extends Enemy {

    private ArrayList<Float> x = new ArrayList<>();
    private ArrayList<Float> y = new ArrayList<>();

    private ArrayList<Float> rotation = new ArrayList<>();

    private boolean firstEnemy = false;

    public E0(float x, float y) {
        super(0, x, y);

        this.x.add(x);
        this.y.add(y);

        this.rotation.add(0.0f);
    }


    @Override
    public void update(int delta) {
        if(firstEnemy) {

            for(int i =  0; i > x.size(); i++) {



            }

        }
    }

    @Override
    public void render() {
        if(firstEnemy) {

            for(int i =  0; i > x.size(); i++) {



            }

        }
    }
}

So, my question is, can I do something in the superclass so I dont need to setup the for() loop again and again in the subclasses? I dont really understand the meaning of an abstract class so if you think it shouldnt be can you be so nice and tell me why? :D

Anyway, thank you.

Depending on the nature of what you do inside the body of these loops you could potentially use the Template Method design pattern. The idea is to put the loop in a method in the base, and introduce a different abstract method that performs a single step of the loop, like this:

public abstract class Enemy {
    ...
    public void render() {
        if(firstEnemy) {
            for(int i =  0; i > x.size(); i++) {
                doRender(i);
            }
        }
    }
    public abstract void doRender(int i);
}

public class E0 extends Enemy {
    ...
    public abstract void doRender(int i) {
        ... // Do the work for a single step of the loop in E0
    }
}
public class E1 extends Enemy {
    ...
    public abstract void doRender(int i) {
        ... // Do the work for a single step of the loop in E1
    }
}
... // And so on

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