标签:style class c java color int
1. this调用成员变量和成员函数
2. this调用构造函数
1. Person.java
public class Person{
String name ;
void
talk(){
System.out.println("my name is " + this.name);
// name是成员变量, 使用成员变量需要格式:对象.成员变量
// this 就代表调用talk的对象
}
}
Test.java
public class Test{
public static void main(String args
[]){
Person p1 = new
Person();
p1.name = "zhangsan"
;
Person p2 = new
Person();
p2.name = "lisi"
;
p1.talk();
p2.talk();
}
}
2. Person.java
public class Person{
String name ;
int age;
string address;
Person(){
System.out.println("无参数的构造函数");
}
Person(String name,int age, String address){
this.name = name ; //this.name (代表成员变量) = name (代表构造函数参数)
this.age = age;
this.address = address;
}
void talk(){
System.out.println("my name is " + this.name);
}
}
3. 如果只想给两个对象的两个成员变量赋值
Person.java
public class Person{
String name ;
int age;
string address;
Person(){
System.out.println("无参数的构造函数");
}
Person(String name , int age){
this.name = name ;
this.age = age;
}
Person(String name,int age, String address){
this(name,age); //会调用类中有两个相同变量的成员函数
//这个this语句只能放在第一句.
this.address = address;
}
void talk(){
System.out.println("my name is " + this.name);
}
}
标签:style class c java color int
原文地址:http://www.cnblogs.com/iMirror/p/3733431.html