static声明的属性为全局属性,声明的方法可以直接通过类名调用
使用static方法时,只能访问static声明的属性和方法,而非static声明的属性和方法是不能访问的
案例:
class Person{
String name;
private static String country="北京";
public Person(String name ) {
this.name=name;
}
public void tell() {
System.out.println(name+country);
}
public static String getCountry() {
return country;
}
public static void setCountry(String country) {
Person.country = country;
}
}
因为country属性通过static关键字声明,因此使用set方法时也要加上static,并且可以通过类名Person直接调用
this关键字
1、表示类中的属性和调用方法
2、调用本类中的构造方法
3、表示当前对象
class People{
private String name;
private int age;
public People(String name,int age){
this();//必须放首行,直接调用构造方法
this.name=name;//this调用当前类中的对象
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 Test04 {
public static void main(String[] args) {
People p=new People("张三",30);
p.tell();
}
}
输出结果:
无参数构造方法
张三30