Can I have an empty Java class?

走远了吗. 提交于 2019-12-19 04:17:26

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/28090223/can-i-have-an-empty-java-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!