Java 构造函数不可以继承,因此不能被重写,但可以被重载

Constructors 是在一个类创建的时候,用户创建类实例的时候被调用的特殊函数。它不是一个类的成员函数,它只能代表这个类本身。

不可以创建一个继承的子类时,用父类的构造方法创建子类。

[java] view plain copy

  1. public class main {

  2. public static void main (String[] arg){

  3. Son s = new Son (); // code 1

  4. }

  5. }

  6. class Father{

  7. public Father (){

  8. System.out.println("Father Construtor");

  9. }

  10. public Father (int x){

  11. System.out.println("Father Construtor " + x);

  12. }

  13. public void Father (){

  14. System.out.println("Father member function");

  15. }

  16. }

  17. class Son extends Father {

  18. public Son (){

  19. super(1);

  20. System.out.println("Son Construtor");

  21. }

  22. public void Father(){

  23. System.out.println("Inherited Father member function.");

  24. super.Father();

  25. }

  26. }

如果在创建子类的时候,使用父类的构造方法,写成这样:

Son s = new Father ();

这时候,编译器会报“Type mismatch: cannot convert from Father to Son” 错误。

如果我们进行强制转换,如下:

Son s = (Son)new Father ();

这时候,编译器无法发现有什么错误,但是运行的时候会抛出下面异常。

Exception in thread "main" java.lang.ClassCastException: Father cannot be cast to Son at main.main(main.java:4)

父类无法转换成子类。其本质上,创建的仍是一个父类。

如果在Son类中,增加父类constructor的函数。

[java] view plain copy

  1. public Father (){

  2. }

去尝试重载父类constructor,编译器会报错。

所以,编译器如果要构造一个类,必须要有和类名字相同的构造函数才可以。

也就是说,构造函数是用来造唯一的东西的。不能用一个构造函数即造爸爸,又造儿子。这样身份就乱了。

你可能感兴趣的:(Java 构造函数不可以继承,因此不能被重写,但可以被重载)