super关键字的作用

java中的super关键字是一个引用变量,用于引用父类对象。关键字“super”以继承的概念出现在类中。

主要用于以下情况:1.调用父类的方法   2.调用父类的变量  3.调用父类的构造方法

1.调用父类的方法

当我们要调用父类方法时使用。父类和子类都具有相同的命名方法,那么为了解决歧义,我们使用super关键字。这段代码有助于理解super关键字的使用情况。

/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
} /* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
} // Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message(); // will invoke or call parent class message() method
super.message();
}
} /* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student(); // calling display() of Student
s.display();
}
}

输出:

This is student class
This is person class

2.调用父类的变量

当子类和父类具有相同的数据成员时,会发生此情况。在这种情况下,JVM可能会模糊不清。我们可以使用以下代码片段更清楚地理解它:

/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
} /* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180; void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
} /* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}

输出:

Maximum Speed: 120

3.调用父类的构造方法

super关键字也可以用来访问父类的构造函数。更重要的是,super关键字可以根据情况调用参数和非参数构造函数。以下是解释上述概念的代码片段:

/* superclass Person */
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
} /* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super(); System.out.println("Student class Constructor");
}
} /* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}

输出:

Person class Constructor
Student class Constructor

我们通过子类构造函数使用关键字'super'调用父类构造函数。

补充:

1.调用super()必须是子类构造函数中的第一条语句。

最新文章

  1. BZOJ 4742: [Usaco2016 Dec]Team Building
  2. c语言中在引用math库后,编译出现错误(.text+0x9c):对‘sqrt’未定义的引用的解决办法
  3. JavaScript函数表达式
  4. 项目:DoubleFaceCamera
  5. C#实现图标批量下载
  6. MySQL学习基础 之 起航篇
  7. 2016年11月21日 星期一 --出埃及记 Exodus 20:12
  8. 乐够GO应用源码完整版
  9. Quartz1.8.5例子(六)
  10. Asp.net管道 (第二篇)
  11. Android Bitmap与DrawAble与byte[]与InputStream之间的转换工具类【转】
  12. TODOList项目
  13. linux下的framebuffer显示图片
  14. JDK的安装和Java环境变量配置
  15. telnet操作memcache
  16. XMLHttpRequest状态码及相关事件
  17. 模型评估——ROC、KS
  18. CHKDSK/f
  19. Solr系列五:solr搜索详解(solr搜索流程介绍、查询语法及解析器详解)
  20. iOS NSError

热门文章

  1. Springboot + redis + 注解 + 拦截器来实现接口幂等性校验
  2. springboot#下载文件
  3. 「CF1004E」Sonya and Ice Cream
  4. JS enter键一键登录
  5. video-editing
  6. zookeeper logs is missing zookeeper 日志丢失
  7. 还是应该立个flag
  8. Linux开机流程及运行级别
  9. 082、Java数组之数组传递之简化理解
  10. vue ref父子组件传值