当前位置: 移动技术网 > IT编程>开发语言>Java > 举例讲解Java编程中this关键字与super关键字的用法

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

2019年07月22日  | 移动技术网IT编程  | 我要评论

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++直接用基类的名字来调用。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网