当前位置: 代码迷 >> J2SE >> 对静态方法(main)不能调用非静态方法 理解不了,该怎么解决
  详细解决方案

对静态方法(main)不能调用非静态方法 理解不了,该怎么解决

热度:42   发布时间:2016-04-24 12:23:02.0
对静态方法(main)不能调用非静态方法 理解不了
Java code
public class MainTest {    TT t = new TT();    public void go() {        System.out.println("is going");    }        public static void main(String[] args) {        t.play();        go();    }}class TT {    public void play() {        System.out.println("TT play");    }}

代码如上。我知道main方法是静态的 ,但是就是不能理解一些用法。比如上面的代码。
 t.play(); 和go();都调用错了。
为什么把 TT t = new TT(); 放到main方法里面以后,t.play()就能调用呢,
go方法又该怎么调用呢
很菜的问题。希望高手解答下

------解决方案--------------------
class Test
{
public Test()
{
//这里是定义构造函数,默认的不写也可以
}
T t;//这里是成员变量
public static void main(String[] args)
{
T t;//这里是局部变量
new Test();//可以认为是调用构造函数,new对象,这里不是定义构造函数
}
}
------解决方案--------------------
探讨
想请问下创建对象MainTest m = new MainTest(); 为什么要写在main()方法以内呢。写在外面就不能
用m.go()这个形式了
  相关解决方案