栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

举例讲解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:workspaceJavaproject261super>javac -d . *java 
 
D:workspaceJavaproject261super>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++直接用基类的名字来调用。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/150399.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号