Java面向对象编程时,this有以下三种用法:
1、表示类中的属性和调用方法;
2、调用本类中的构造方法;
3、表示当前对象。
第1、2种用法实例:
package com.jike.thisDemo;
class People{
private String name;
private int age;
public People(String name,int age) {
this(); //调用本类中的构造方法
this.name =name; //表示类中的属性
this.age = age;
}
public People() {
System.out.println("无参数构造方法");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public void tell(){
System.out.println("姓名:"+this.getName()+" 年龄:" +this.getAge());
}
}
public class test01 {
public static void main(String[] args) {
People p = new People("张三", 30);
p.tell();
}
}
输出:
无参数构造方法 姓名:张三 年龄:30
第三种用法实例:
package com.jike.thisDemo;
class People1{
public void tell(){
System.out.println(this); //表示当前对象
}
}
public class test02 {
public static void main(String[] args) {
People1 p = new People1();
System.out.println(p); //输出对象p
p.tell(); //也是输出对象p
}
}
输出:
com.jike.thisDemo.People1@77556fd com.jike.thisDemo.People1@77556fd
用于比较对象是否相同。
static关键字:
1、使用static声明属性:全局属性
2、使用static声明方法,直接通过类名调用,即为静态方法
注意:使用static方法的时候,只能访问static声明的属性和方法,而非static声明的属性和方法是不能访问的。静态方法不能调用非静态方法和属性。
package com.jike.staticDemo;
class Person{
String name;
static String country="北京";
public Person(String name) {
this.name=name;
}
public void tell() {
System.out.println("姓名:"+name+"\t国家:"+country);
}
}
public class test01 {
public static void main(String[] args) {
Person per1=new Person("张三");
Person.country="上海";
per1.tell();
Person per2=new Person("李四");
// per2.country="上海";
per2.tell();
}
}
输出:
姓名:张三 国家:上海 姓名:李四 国家:上海
静态方法不能调用非静态方法和属性:
package com.jike.staticDemo;
public class test02 {
private static int a=5;
public static void main(String[] args) {
tell();
System.out.println(a);
}
public static void tell() {
System.out.println("hello");
}
}
输出:
hello 5