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