Flower(String s, int petals) {
this(petals);
//! this(s); // Can't call two!
this.s = s; // Another use of "this"
System.out.println("String & int args");
}新手求指点刚看到this。。一直不明白如上有2个this
this(petals);
//! this(s); // Can't call two!
this.s = s; // Another use of "this"
System.out.println("String & int args");
}新手求指点刚看到this。。一直不明白如上有2个this
// Calling constructors with "this"
public class Flower {
private int petalCount = 0;
private String s = new String("null"); Flower(int petals) {
petalCount = petals;
System.out.println( "Constructor w/ int arg only, petalCount= " + petalCount);
} Flower(String ss) {
System.out.println("Constructor w/ String arg only, s=" + ss);
s = ss;
} Flower(String s, int petals) {
this(petals);
// ! this(s); // Can't call two!
this.s = s; // Another use of "this"
System.out.println("String & int args");
} Flower() {
this("hi", 47);
System.out.println("default constructor (no args)");
} void print() {
// ! this(11); // Not inside non-constructor!
System.out.println("petalCount = " + petalCount + " s = " + s);
} public static void main(String[] args) {
Flower x = new Flower();
x.print();
}
} // /:~
所以,this(petals);就等于Flower(petals)
后面,this.s ,this指的是Flower这个类,那么this.s指的是flower的s,就是数据域当中的
private String s = new String("null");这个s最后面那个s,很正常,是指形式参数s
this.s -- 是创建的实例对象的 s属性
this(petals) ;调用 Flower(petals) 构造函数 ;
Java语言把this隐藏了,有一些语言,比如Python,是明确作为函数的第一个参数的。
比如:def print(self)
注:Python的self和java的this是一样的。这样是不是好理解一点。
this.方法名():这个意思本对象调用普通方法
this.s = s;//给成员变量赋值
下面的this.s=;
指的是把当前的成员变量s赋值为传递进来的局部变量s,就是你的形参。
this.方法 : 表示调用本类中的方法,如果本类中没有则从父类中查找;
this() : 调用本类中的其它构造方法
this : 单独的一个this表示当前对象 ;查找范围:先从子类中查找,如果没有则从父类中查找。Flower(String s, int petals) {
this(petals); //表示调用父类中只有一个参数的构造方法,
//! this(s); //调用父类中的构造方法 // Can't call two!
this.s = s; //表示调用本类中的属性 // Another use of "this"
System.out.println("String & int args");
}
this的几个关键作用都给你写出来了,你先记下,在以后用的时候你就慢慢的体会,时间长了你就会理解的,this是比较难以理解的!
this.xxx 表示当前对象中的 xxx 字段this.s = s;这里如果写成 s = s; 的话,那就不分不出来哪个是参数中的 s,哪个是这个对象成员变量的 s 了,如果没有重名的话,这个 this 是可以省略的,呵呵。this.yyy() 表示当前对象中的 yyy 方法
this.方法 : 表示调用本类中的方法,如果本类中没有则从父类中查找;
this() : 调用本类中的其它构造方法
this : 单独的一个this表示当前对象 ;查找范围:先从子类中查找,如果没有则从父类中查找。Flower(String s, int petals) {
this(petals); //表示调用父类中只有一个参数的构造方法,
//! this(s); //调用父类中的构造方法 // Can't call two!
this.s = s; //表示调用本类中的属性 // Another use of "this"
System.out.println("String & int args");
}