读书人

java中的this解决方法

发布时间: 2013-07-16 22:38:05 作者: rapoo

java中的this
public class Test1
{
public static void main(String[] args) {
b aa=new b();
}
}
class a
{
int num=0;
String name;
public a(){
System.out.println("大家好!我叫:");
}
}
class b extends a
{
String name;
public b(){
int shu=2;
this.name="张三"; //这是第2句
System.out.println("我叫"+name+"我今年"+shu+"岁。");
}
}
在Java书中说this在构造函数中只能出现在第一句,可是这里在第二句也可以正常运行啊,求大神讲解 this
[解决办法]
你的this只是赋值,在第几句都可以,说this在第一句是调用其他构造函数的时候,估计楼主没仔细看书!
[解决办法]
你的this是指对象,构造函数的this是this()----》构造函数方法,LZ别搞混了。
函数,对象要区分
[解决办法]


class Person{
String name;
int age;
public Person(){
System.out.println("student");
}
public Person(String name,int age){
this();
this.name = name;
this.age = age;
System.out.println("worker");
}
}

public class TestThis {

public static void main(String[] args) {
new Person("zhangsan",25);

}

}

像这种调用构造函数的时候this()必须放在第一行,不然就会报错

读书人网 >J2SE开发

热点推荐