Java编译器super()构造函数常规 [英] Java compiler super() constructor generals

查看:123
本文介绍了Java编译器super()构造函数常规的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我是Java的新手,最近一直在阅读很多有关Java的知识和经验。当编译器插入自动代码时,我有一个关于继承方法和扩展类的问题。

I'm new to Java and have been reading a lot about it lately to get more knowledge and experience about the language. I have a question about inherited methods and extending classes when the compiler inserts automatic code.

我一直在阅读,如果我使用某些方法创建A类,其中包括一个称为 checkDuePeriod(),然后创建扩展了类A及其方法的类B。

I've been reading that if I create class A with some methods including lets say a method called checkDuePeriod(), and then create a class B which extends class A and its methods.

如果我再调用方法 checkDuePeriod()而不使用 super.checkDuePeriod()语法,在编译期间,编译器将包括 super。 checkDuePeriod()之前,还是编译器在编译类时自动包含 super()构造函数的事实暗示B类从A类调用的方法的 super。调用?

If I then call the method checkDuePeriod() within class B without using the super.checkDuePeriod() syntax, during compilation will the compiler include the super. before checkDuePeriod() or will the fact that the compiler includes the super() constructor automatically when compiling the class imply the super. call of the methods that class B calls from class A?

对此我有些困惑。

推荐答案

父类的常规方法的实现不是 not 在子类中自动调用的,但是必须在子类的构造函数中调用超类的构造函数的形式。

The super class's implementation of regular methods is not automatically invoked in sub classes, but a form of the super class's constructor must be called in a sub class's constructor.

在某些情况下,对 super()<的调用/ code>是隐含的,例如,当超类具有默认(无参数)构造函数时。但是,如果超类中没有默认构造函数,则子类的构造函数必须直接或间接调用超类构造函数。

In some cases, the call to super() is implied, such as when the super class has a default (no-parameter) constructor. However, if no default constructor exists in the super class, the sub class's constructors must invoke a super class constructor directly or indirectly.

默认构造函数示例:

public class A {
    public A() {
        // default constructor for A
    }
}

public class B extends A {
    public B() {
        super(); // this call is unnecessary; the compiler will add it implicitly
    }
}

没有默认构造函数的超类:

Super class without default constructor:

public class A {
    public A(int i) {
        // only constructor present has a single int parameter
    }
}

public class B extends A {
    public B() {
        // will not compile without direct call to super(int)!
        super(100);
    }
}

这篇关于Java编译器super()构造函数常规的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆