软件编程
位置:首页>> 软件编程>> java编程>> 举例讲解Java编程中this关键字与super关键字的用法

举例讲解Java编程中this关键字与super关键字的用法

作者:全速前行  发布时间:2023-03-09 01:46:02 

标签:Java,this,super

this
总要有个事物来代表类的当前对象,就像C++中的this指针一样,Java中的this关键字就是代表当前对象的引用。
它有三个主要的作用:
1、在构造方法中调用其他构造方法。
      比如有一个Student类,有三个构造函数,某一个构造函数中调用另外构造函数,就要用到this(),而直接使用Student()是不可以的。
2、返回当前对象的引用。
3、区分成员变量名和参数名。
看下面的例子:


public class Student
{
 private String name;
 private int age;
 private String college;
 public Student()
 {
   age = 20;
 }
 public Student(String name)
 {
   this();//can not be call Student,only use this() method.
   this.name = name;
   System.out.println("this student name is "+name);
 }
 public Student(String name,String college)
 {
   this(name);//C++中可以直接用Student(name)调用其他构造函数
   this.college = college;
   System.out.println("this student name is "+name+" college is "+college);    
 }

public Student upgrade()
 {
   age++;
   return this;
 }

public void print()
 {
   System.out.println("name is: "+name
       +" age is: "+age
       +" college is: "+college);
 }

public static void main(String[] args)
 {
   Student student1 = new Student("linc");
   Student student2 = new Student("linc","shenyang college");
   student2.upgrade().print();
 }
}

迷失在茫茫的对象海洋时,不要忘了用this来找到自我。

super
super是this的父辈。从面相对象的角度说,这两个概念是很好理解的。
子类从父类继承过来,父类的protected及以上的属性和方法在子类中是天生就具有的。那么,为什么还要有super这个关键字?
第一、看父类的构造
子类构造时要先调用父类的默认构造函数的,这与C++的构造属性一致。当父类有多个构造函数时,你需要指定调用哪个。这是就需要使用super(arg1,arg2...)。
需要注意的是,在子类的构造函数中调用基类的构造函数时,必须要把super写作最前面,否则报错。
第二,在子类覆盖父类的一些方法中再调用父类的此方法。大家都知道,在子类中覆盖父类的一些方法是面向对象中多态的一种方式,而因为其他种种原因,需要在此方法中调用父类的此方法,用以区分,此时需要使用super来完成。


public class ClassLeader extends Student
{
 private String duty;
 public ClassLeader()
 {
   duty = "class monitor";
 }
 public ClassLeader(String duty,String name,String college)
 {
   super(name,college);
   this.duty = duty;
 }

public void print()
 {
   super.print();
   System.out.println("duty is " + duty);
 }

public static void main(String[] args)  
 {  
   ClassLeader leader = new ClassLeader("life","linc","shenyang");
 leader.print();
 }  

}

将两个类文件放在同一个目录,编译并运行:


D:\workspace\Java\project261\super>javac -d . *java

D:\workspace\Java\project261\super>java ClassLeader

运行结果:


this student name is linc
this student name is linc college is shenyang
name is: linc age is: 20 college is: shenyang
duty is life

看看在其他语言中是怎样来处理的:
C#中提供了base关键字来完成super相似的功能,C++直接用基类的名字来调用。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com