来自其他类的新类 - java [英] New class from other class - java
本文介绍了来自其他类的新类 - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从另一个类创建一个新类。在类的构造函数中创建或在类的字段中创建,有什么区别?
我尝试过的方法:
公共类GUI {
//要运行的主要gameEngine实例
GameEngineImpl gameEngine = new GameEngineImpl(); < br $>
公共GUI(){
//要运行的主要gameEngine实例
GameEngineImpl gameEngine = new GameEngineImpl() ;
解决方案
字段初始值设定项在构造函数中的代码之前运行。它们允许您将字段初始化为简单值,而不引用构造函数参数。
- 如果需要使用构造函数参数来创建值,然后你必须在构造函数中初始化字段。
- 如果一个字段的初始化依赖于同一个类中的另一个字段,通常最好将它放在构造函数中。
- 如果你需要复杂的初始化逻辑,最好将它放在构造函数中。
除此之外,没有真正的区别
creating a new class from another class. create in the constructor of the class or create in the fields of the class, whats the difference?
What I have tried:
public class GUI {
// main gameEngine instance to run
GameEngineImpl gameEngine = new GameEngineImpl();
public GUI() {
// main gameEngine instance to run
GameEngineImpl gameEngine = new GameEngineImpl();
解决方案
Field initializers run before the code in the constructor. They allow you to initialize a field to a simple value, with no reference to constructor parameters.
- If you need to use constructor parameters to create the value, then you have to initialize the field in the constructor.
- If the initialization of one field depends on another field from the same class, it's usually best to put that in a constructor.
- If you need complex initialization logic, it's best to put that in a constructor.
Beyond that, there's no real difference.
这篇关于来自其他类的新类 - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文