为什么我需要在扩展抽象类中使用另一个构造函数?

时间:2016-01-23 11:23:28

标签: java inheritance constructor abstract-class default-constructor

我遇到过这个问题,我想知道这有什么区别:

var culture = new CultureInfo("sl-SI");
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
        Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator = ",";
        Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator = ".";

为什么我必须定义abstract class Abstract { Abstract() { System.out.println("Abstract.Abstract()"); } Abstract(String s) { System.out.println("Abstract.Abstract(String)"); } void test() { System.out.println("Abstract.test()"); } void test(String s) { System.out.println("Abstract.test(s)"); } } abstract class Base extends Abstract { } class Sub extends Base { Sub(String s) { super(s); // undefined constructor } void subTest(String s) { super.test(s); // why is this all right then? } } 构造函数以使其可编译但Base(String s)调用没有定义任何内容?

2 个答案:

答案 0 :(得分:1)

Java在任何类中为您提供默认构造函数(即使您不自己定义一个),这意味着您在类<span class="color">This is colored</span> 中有Base()默认构造函数,但不是任何其他构造函数(带有参数的构造函数,例如Basebecause constructors are not inherited

此外,扩展一个类通过继承为您提供方法,因此调用Base(String s)是合法的,因为super.test(s)具有从Base继承的方法test(String s)

答案 1 :(得分:0)

因为Base只定义了一个构造函数,所以no-args默认调用超类no-args构造函数。

现在,Sub可以使用哪些超类cunstructors?只有一个。