如何使 Main 类实例的范围存在于整个类中
是否有可能使主类实例的范围存在于整个主类中?我试图从我的对象类运行方法,但这些方法位于主类中。 简化的主类如下所示
public static void main (String[] args)
{
MyMain x = new MyMain ();
}
public void change()
{
System.out.println("whatever");
}
MyMain()
{
System.out.println("--1--");
}
现在,如果我想从对象调用方法 public void change,我通常只使用 x.change();或 MyMain.x.change;在对象中,但是x的范围显然没有到达对象。有没有办法让对象的范围更大,同时只说 MyMain x = new MyMain();一次?
Is it possible to make the scope of an instance of a main class exist through the whole main class? I am trying to run methods from my object classes, but the methods are in the main class.
The simplified main class looks like this
public static void main (String[] args)
{
MyMain x = new MyMain ();
}
public void change()
{
System.out.println("whatever");
}
MyMain()
{
System.out.println("--1--");
}
Now if I wanted to call the method public void change from the object, I would normally just use x.change(); or MyMain.x.change; in the object, but the scope of x is obviously not reaching the object. Is there a way make the scope bigger for the object while only saying MyMain x = new MyMain(); once?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使 xa 静态变量:
或使更改函数静态,这样您就不需要实例来调用它:
Make x a static variable:
or make the change function static, so you don't need an instance to call it:
我会将主对象作为对其他对象的依赖传递。或者更好地隔离一个接口(例如 IChangeable)并传递它而不是实际对象。
作为解决方法,您可以将主对象设为 Singleton
I would pass main object as dependency to other objects. Or better segregate an interface (something like IChangeable) and pass it instead of actual object.
As a workaround you could make main object a Singleton
您必须选择扩大范围。要么将对 MyMain 的引用传递到每个应该从那里调用方法的对象中,要么添加一个保存 MyMain 的静态变量。
第一种方法很容易完成,因为它可能会创建所有其他对象。因此,编写
new Foo(this)
而不是new Foo()
会很容易。这称为控制反转。另一种方法实际上会引入一个全局变量。这种模式称为单例模式。
在这里寻找一个实现:(来自谷歌的第一次点击)
http://radio-weblogs.com/0122027/stories/2003 /10/20/implementingTheSingletonPatternInJava.html
You have to options for growing the scope. Either you pass a refernce to MyMain into every object that should call a method from there, or you add a static variable holding your MyMain.
The first approach could be easily done because probably it creates all other objects. So it would be easy to write
new Foo(this)
instead ofnew Foo()
. This is called Inversion of Control.The other method would in-fact introduce a global variable. This pattern is called singleton-pattern.
Look here for an implementation: (first hit from google)
http://radio-weblogs.com/0122027/stories/2003/10/20/implementingTheSingletonPatternInJava.html