首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

java中的this解决方法

2013-07-16 
java中的this public class Test1 {public static void main(String[] args) {b aanew b()} } class a {

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()必须放在第一行,不然就会报错

热点排行