一、this关键字
1.表示类中的属性和调用方法
.
2.调用本类中的构造方法
代码示例:
class People {
private String name;
private int age;
public People(String name, int age) {
// 2、this可以表示本类中的构造方法
this();
// 1、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() {
// 1、this可以表示类中的属性和调用方法
System.out.println("姓名:" + this.getName() + " 年龄:" + this.getAge());
}
}
public class ThisDemo {
public static void main(String[] args) {
People p = new People("哈士奇", 4);
p.tell();
}
}
.
3.表示当前对象
代码示例:
class People1 {
public void tell() {
// 3、this可以表示当前对象
System.out.println(this);
}
}
public class ThisDemo02 {
public static void main(String[] args) {
People1 p = new People1();
System.out.println(p);
p.tell();
}
}
.
.
.
二、static关键字
1.使用static声明属性(全局属性)
代码示例:
class Person {
String name;
private static String country = "北京";// 静态:大家共有的全局属性
public Person(String name) {
this.name = name;
}
public static String getCountry() {
return country;
}
public static void setCountry(String country) {
Person.country = country;
}
public void tell() {
System.out.println("姓名:" + name + " 出生地:" + country);
}
}
public class StaticDemo01 {
public static void main(String[] args) {
Person.setCountry("上海");// 不管是属性还是方法,只要静态的,都是通过类名来调用
Person p1 = new Person("哈士奇");
// Person.country = "上海";//静态属性通过类名来调用
p1.tell();
Person p2 = new Person("小魔兽");
// p2.country = "上海";
p2.tell();
Person p3 = new Person("大狮子");
// p3.country = "上海";
p3.tell();
}
}
.
2.使用static声明方法
直接通过类名调用
3.注意点:
使用static方法的时候,只能访问static声明的属性和方法,而非static声明的属性和方法是不能访问的。
示例:
i不是静态变量,不能调用
.
.
.
三、super关键字
1.子类重写了父类方法,调用子类方法时,为了执行父类的方法就会用到一个super
示例:
2. 上述的子类对象实例化之前,必须先调用父类中的构造方法,然后再调用子类中的构造方法。其实子类的构造方法中就有super.父类();
.
.
.
四、final关键字
1.final关键字在java中被称为完结器,表示最终的意思。
2.final能声明类、方法、属性:
a.使用final声明的类不能被继承
b.使用final声明的方法不能被重写
c.使用final声明的变量变成常量,是不可以被修改 的,且一定要大写