序言
简单说一下Java语言中super关键字与this关键字的作用,看看他们的特点
this关键字
作用 :this代表当前对象的引用
- this.data: 访问当前类的属性
- this.func(): 访问本类的其他成员方法
- this(): 调用本类其他的构造方法
this.data
当我们类中方法的参数名与字段名相同时,我们通过this.data 来代表是字段,当然如果名字不同时,字段也可以不加this,不过我们代码风格要求尽量使用this,我们要风格给用好
带有this
class Person {
public String name;
public void setName(String name) {
this.name = name; // this.name表示字段
}
public void sleep() {
System.out.println(this.name + " sleep()");
}
}
public class TestDemo2 {
public static void main(String[] args) {
Person per = new Person();
per.setName("张三");
per.sleep();
}
}
不带this
class Person {
public String name;
public void setName(String name) {
name = name;
}
public void sleep() {
System.out.println(this.name + " sleep()");
}
}
this.func()
这个没什么好说的,代码风格
class Person {
public String name;
public void sleep() {
this.eat(); // 和eat();逻辑一样,最好带上
System.out.println(this.name + " sleep()");
}
public void eat() {
System.out.println("eat()");
}
}
public class TestDemo2 {
public static void main(String[] args) {
Person per = new Person();
per.name = "张三";
per.sleep();
}
}
this()
这个就要求的就有些多了,我们仔细看看
class Person {
public String name;
public int age;
public Person() {
this.sleep();
}
public Person(int age) {
this();
this.age = age;
}
public Person(String name) {
this(11);
this.name = name;
}
public void sleep() {
System.out.println("sleep()");
}
}
public class TestDemo2 {
public static void main(String[] args) {
Person per = new Person(18);
}
}
我来说几个重要的点
- 构造方法可以自动生成一个不带参数的构造方法
- this()在一个构造方法中可以调用另一个,该代码在首行,这个首行使代码行的首行
super关键字
作用:代表对父类的引用
- super(): 调用父类的构造方法
- super.data: 访问父类的属性
- super.func(): 访问父类的方法
super()
子类new一个对象时,要先帮助父类进行构造,否则会报语法错误,这就是super()的作用
class Animal {
public String name;
public Animal(String name) {
this.name = name;
}
public void sleep() {
System.out.println(this.name + " sleep()");
}
}
class Cat extends Animal {
public Cat(String name) {
super(name);
}
}
public class TestDemo {
public static void main(String[] args) {
Cat cat = new Cat("mimi");
cat.sleep();
}
}
这个我也说一下
- super()也是只能存在首行
super.data
class Animal {
public String name;
public int age;
public void fun() {
System.out.println(this.age);
}
}
class Cat extends Animal {
public Cat(int age) {
super.age = age;
}
}
public class TestDemo {
public static void main(String[] args) {
Cat cat = new Cat(18);
cat.fun();
}
}
super.func()
class Animal {
public String name;
public int age;
public void sleep() {
System.out.println("sleep()");
}
}
class Cat extends Animal {
public Cat() {
super.sleep();//显示调用
}
}
public class TestDemo {
public static void main(String[] args) {
Cat cat = new Cat();
//cat.fun();
}
}
super总结
你会发现,在super这里,我们都是在构造方法里面使用,实际上,如果在方法外,注意使成员方法内,不仅仅使构造方法.会出现语法错误,this也一样
class Cat extends Animal {
public Cat() {
}
super.sleep(); //只能在方法里面
}
总结
this和super都不能出现静态方法中