【知了堂学习笔记】java中this和super的用法

来源:互联网 发布:血与酒 石之心 知乎 编辑:程序博客网 时间:2024/06/06 00:50

this

this表示当前类的对象,this可以用来修饰属性、方法、构造器。它在方法内部使用,即这个方法所属对象的引用;普通方法中,this总是指向调用该方法的对象;构造方法中,this总是指向正要初始化的对象。

this的用法:

1.直接引用,即this指向当前对象本身

public class TestDemo {public int age = 2;public void show() {this.age=3;System.out.println(age);}public static void main(String[] args) {TestDemo a = new TestDemo();a.show();}}

2.区分同名的全局变量和局部变量

public class TestDemo {public int age = 2;public void show(int age) {System.out.println(this.age);System.out.println(age);}public static void main(String[] args) {TestDemo a = new TestDemo();a.show(6);}}


3.调用本类的其它构造方法

public class TestDemo {public int age;public TestDemo(int age) {this.age = age;System.out.println(age);}public TestDemo() {this(8);}public static void main(String[] args) {TestDemo a = new TestDemo();}}

this在使用过程中需注意以下几点:

1. this不能用于static方法,因为在static方法中不可以访问非static的成员 (不能用于mian方法) 。static修饰的方法是属于类的,该方法的调用者可能是一个类,而不是对象。如果使用的是类来调用而不是对象,则 this就无法指向合适的对象。所以static 修饰的方法中不能使用this。

2.通过this调用其它构造方法,必须位于方法(构造方法)第一句。


super

代表父类的对象,可以访问父类的属性、方法和构造器。

super的用法:

1.直接引用

public class TestDemo {public String name = "天天";}public class DemoSon extends TestDemo {public int age = 6;public void show() {System.out.println(super.name + "  " + age);}public static void main(String[] args) {DemoSon b = new DemoSon();b.show();}}

2.子类与父类中的成员变量或方法同名

public class TestDemo {public String name = "天天";public void show() {System.out.println(name);}}public class DemoSon extends TestDemo {public String name ="乐乐";public void show() {System.out.println(super.name);super.show();}public static void main(String[] args) {DemoSon b = new DemoSon();b.show();}}

3.调用父类的构造函数

public class TestDemo {public String name = "天天";public TestDemo() {System.out.println("无参数的父类构造方法");}public TestDemo(String name) {System.out.println(name);}}public class DemoSon extends TestDemo {public String name ="乐乐";public DemoSon() {super("可乐");}public static void main(String[] args) {DemoSon b = new DemoSon();}}

super在使用时需要注意以下几点:

1.super同样不能用于static方法(不能用于mian方法)。

2.通过super调用父类的构造方法,必须位于方法(子类构造方法)第一句。

3.Java不支持super多级调用,即super.super。


除了上面在使用this和super时需要注意的以外,还有几点比较重要。

1.this和super不能同时出现在一个构造函数里面。

2.如果没有显示调用超类的构造器,那么子类构造器就会默认调用超类的无参构造器,如果超类没有无参构造器,那么编辑器就会报错。例如:在父类中定义了一个有参数的构造函数(不定义,就只有默认不带参数的构造函数),子类通过super(),来调用父类的构造函数,此时编译器就会报错,超类中没有可用的默认构造器。


原创粉丝点击