Can I have an empty Java class?

2019-02-15 14:07发布

I'm creating a grid based game.

I need to implement a set of obstacles that take random positions within the grid. I've created an abstract class ALifeForm, that holds the common methods for every item within the grid. Obviously, abstract classes can't be initialised, so I was going to create a new class AObstacle, which will extend ALifeForm.

Only issue is, my AObstacle class isn't specialised. All the methods it needs are within ALifeForm.

Can I have an empty class? Is it bad programming practice? And if so, what can I implement instead?

2条回答
Evening l夕情丶
2楼-- · 2019-02-15 14:39

Of course...

class AObstacle { }

(Plus whatever inheritance model you're using.) There's nothing stopping you from doing this.

Remember that a class isn't really a thing that you're defining. A type is. The class is just the language/syntax construct used to describe the type. If the type being described has no attributes or operations aside from the inheritance model, then there's nothing else to add to it.

Though you are adding one thing. You're giving it a name. It doesn't sound like much, but defining a semantic concept with a concrete name (particularly in a statically typed environment) is very important. Your type now has an identity apart from other types in the system. If things are added to it later, there's a place to add them without refactorings and breaking changes.

查看更多
乱世女痞
3楼-- · 2019-02-15 14:45

Well to do it you don't need to have an abstract class and a class that extends it, or an empty class(wich is possible too).

First way:

You just need to implement two classes: The class that contains the methods and the variables you need to use and the second calss that has an instance of your first class:

public class A{
  public void firstMethod(){
    //do your stuff here
  }
....
}

public class B{
  public static void main(String[] args) {
   A a=new A(); //instantiate your class here 
   a.firstMethod();// then just use its methods
  }
}

Because if you implement a class that extends an abstract class it should implement all its methods.

Second way:

  • Or if you want your second class to be specialized you could have :

your first class wich should not be abstract and the second one can extend it and use all its methods, and have its specific methods

查看更多
登录 后发表回答