super()用于调用父构造函数吗? 请解释super()。
当前回答
Super是一个关键词。在子类方法定义中使用它来调用父类中定义的方法。父类的私有方法不能被调用。只有public和protected方法可以被super关键字调用。类构造函数也使用它来调用父类的构造函数。
点击这里查看进一步的解释。
其他回答
来源文章:Java:调用super()
是的。Super(…)将调用超类的构造函数。
说明:
独立的例子:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
打印:
Constructing an animal: From Dog constructor
Constructing a dog.
这是正确的。Super用于调用父构造函数。假设你有这样一个代码块
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
然后你可以给成员变量n赋一个值。
我愿意与代码分享我所了解的一切。
java中的super关键字是一个引用变量,用于引用父类对象。它主要用于以下情况:-
1. super与变量的使用:
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
super with的使用方法:
/* 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
3.super与构造函数的使用:
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()不带参数地调用父构造函数。
它也可以与参数一起使用。例如super(argument1),它将调用接受一个argument1类型形参的构造函数(如果存在的话)。
它还可以用于从父类调用方法。即super.aMethod ()
更多信息和教程在这里
例如,在selenium自动化中,你有一个PageObject,它可以像这样使用它的父类构造函数:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?