class Df
{
float a,b;
Df(int x,int y)
{
a=x;
b=y;
}
public static void main(String args[])
{
Df gg=new Df(2,3);
System.out.println("a="+this.a+"b="+this.b); //this就是指的是gg , 为什么编译出错,不解
}
}
{
float a,b;
Df(int x,int y)
{
a=x;
b=y;
}
public static void main(String args[])
{
Df gg=new Df(2,3);
System.out.println("a="+this.a+"b="+this.b); //this就是指的是gg , 为什么编译出错,不解
}
}
楼主【sure2003】截止到2008-06-27 16:11:46的历史汇总数据(不包括此帖):
发帖数:188 发帖分:8827
结贴数:188 结贴分:8827
未结数:0 未结分:0
结贴率:100.00% 结分率:100.00%
敬礼!
{
Df gg=new Df(2,3);
System.out.println("a="+this.a+"b="+this.b); //this就是指的是gg , 为什么编译出错,不解
}this.只能用在实例方法中,不能用在类方法中
你在main方法中用this,所以他报错了啊
我经常就是,看起来更容易理解
{
String name;
public Person(String name)
{
this.name = name;
}
} 2、假设有一个容器类和一个部件类,在容器类的某个方法中要创建部件类的实例对象,而部件类的构造方法要接受一个代表其所在容器的参数。例如: class Container
{
Component comp;
public void addComponent()
{
comp = new Component(this);
}
}
class Component
{
Container myContainer;
public Component(Container c)
{
myContainer = c;
}
} 3、构造方法是在产生对象时被java系统自动调用的,我们不能再程序中像调用其他方法一样去调用构造方法。但我们可以在一个构造方法里调用其他重载的构造方法,不是用构造方法名,而是用this(参数列表)的形式,根据其中的参数列表,选择相应的构造方法。例如: public class Person
{
String name;
int age;
public Person(String name)
{
this.name = name;
}
public Person(String name,int age)
{
this(name);
this.age = age;
}
}
{
float a,b;
Df(int x,int y)
{
a=x;
b=y;
}
public static void main(String args[])
{
Df gg=new Df(2,3);
System.out.println("a="+gg.a+"b="+gg.b); //this就是指的是gg , 为什么编译出错,不解
}
}
LZ想使用的是this指代当前对象,只有在类方法中这样指代才有意义。如果你定义了:
Df gg1=new Df(2,3);
Df gg2=new Df(4,5);
你在main中用this 指代,你是编译器的话你知道是指的gg1还是gg2?
{
static float a,b;
Df(int x,int y)
{
a=x;
b=y;
}
public static void main(String args[])
{
//Df gg=new Df(2,3);
System.out.println("a="+a+"b="+b);
}
}
你在main方法中去调用,a,b当然用不了了,静态方法是不以调用非静态变量的。你写成上面的那这样,就可以了。
package date;public class Test {
String b;
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(new Test().b);
}}
并且楼主程序里的this 也不就是gg对象。