class Test
{
int x,y;
void output()
{
System.out.println(x);
System.out.println(y);
}
public static void main(String args[])
{
Test tmp;
tmp=new Test();
tmp.output();
}
}对这代码有点不解, Test 类有两个方法,output 方法和 main 方法。main 方法是这个类的入口函数,当执行到 Test tmp 时能定义这个对象吗?! 这好象有点像自己包含自己的问题。
{
int x,y;
void output()
{
System.out.println(x);
System.out.println(y);
}
public static void main(String args[])
{
Test tmp;
tmp=new Test();
tmp.output();
}
}对这代码有点不解, Test 类有两个方法,output 方法和 main 方法。main 方法是这个类的入口函数,当执行到 Test tmp 时能定义这个对象吗?! 这好象有点像自己包含自己的问题。
{
Test tmp;//创建一个Test的对象
tmp=new Test();//实例化这个对象
tmp.output();//通过这个对象调用Test中的output();方法
}
{
int x,y; public static void main(String args[])
{
Test tmp;
tmp=new Test();
tmp.show();
}
void show()
{
Test one=new Test();
one.x=10;
one.y=10;
System.out.println(x); // 这为什么输出 0 ? 上面语句不是已经赋值了吗?
System.out.println(one.x);
System.out.println(y);
System.out.println(one.y);
}
}
one.x=10;
one.y=10;
System.out.println(x); // 这为什么输出 0 ? 上面语句不是已经赋值了吗?
你修改的只是one这个实例指向的x值,它与this是分开两个不同的,one与this根本不是同一个对象,互相不会受到影响
one.x=10;
one.y=10;
System.out.println(x); // 这为什么输出 0 ? 上面语句不是已经赋值了吗?unhappyless_18() ( ) 呵呵 哥们
建议你买本javascjp考试1000例看看
里面很多这种传值的题
对你理解java代码会有极大的帮助的
=============================================================================但这里的 this 和 one 应该是同一个对象呀?
执行我的test2,就会看到你想要的结果了public class test2 {
public test2() {
test1.newperson();
}
public static void main(String[] args) {
test2 test21 = new test2();
}
}public class test1 {
public test1() {
}
public static void newperson(){
System.out.println("new a baby");
}
}
================================================================还有一处不明白:this 和one都是Test类的一个实例,但是它们不是同一个对象!-------------------------------------------------------------------------------那如果在 test类 的构造函数中有 this.x=x 或 this(3,5) ,那用 test one =new test(); 的话,one 这实例对象和 this 不都是同一个吗?! 若不是的话构造函数中不就不能那么用?
你要指向同一个必须是Test one = this;这样
{
public static void main(String[] args)
{
test one=new test(3,5);
}
}class test
{
test(int x,int y)
{
this.x=x;
this.y=y;
}
int x,y;
}
那这里面的 this 对象不等于 one 对象吗?
实参x,y赋值给test的成员变量。
===this只有在一个对象中说才有意义的,调用obj.method时,在method中this就已经转变了obj这个对象了在你的例子中test one是一个test的实例,只有当调用 构造函数,或者one.method时,this才会等于one,在main方法中不存在this(因为静态方法中不存在this)
show()中又实例化了类对象"one",并对类成员变量进行了赋值,你可以将tmp和one看成时人类中的男人和女人,男人有黑眼睛黑皮肤,女人有蓝眼睛白皮肤,那么他们有不同的x,y值,不是类当中的同一个x,y.而且在主函数中对本类(主函数所在的类)进行实例化对象的时,调用本类成员变量时候就是用System.out.println(x);但是在类中的方法实例化对象后就得用方法中类对象调用类成员变量.
而且在本类方法中去实例化本类的对象这种方法是不提倡的,尽量在主函数中去实例化类对象.