gpt4 book ai didi

java - 如果我将一个类的默认构造函数声明为私有(private),为什么它不能被子类化

转载 作者:行者123 更新时间:2023-12-01 07:26:34 26 4
gpt4 key购买 nike

In a class i can have as many constructors as I want with different argument types. I made all the constructors as private,it didn't give any error because my implicit default constructor was public But when i declared my implicit default constructor as private then its showing an error while extending the class. WHY?

这很好用

public class Demo4  {
private String name;
private int age;
private double sal;

private Demo4(String name, int age) {
this.name=name;
this.age=age;
}

Demo4(String name) {
this.name=name;
}

Demo4() {
this("unknown", 20);
this.sal=2000;
}

void show(){
System.out.println("name"+name);
System.out.println("age: "+age);
}
}

不能继承

public class Demo4  {
private String name;
private int age;
private double sal;

private Demo4(String name, int age) {
this.name=name;
this.age=age;
}

Demo4(String name) {
this.name=name;
}

private Demo4() {
this("unknown", 20);
this.sal=2000;
}

void show() {
System.out.println("name"+name);
System.out.println("age: "+age);
}
}

最佳答案

why a class can not be subclassed if i declare its default constructor as private

子类中的构造函数必须调用 super 构造函数(可以是隐式的或显式的),以便完全构造对象。 super 构造函数调用链一直向上直到 Object 类,它是 Java 中所有类的父类(super class)。

如果任何 super 构造函数对子类不可见,则无法完全构造 then 对象。

解决这个问题的一种方法是使父类(super class)中的构造函数 protected 。这样 super 构造函数仅对子类可见。

关于java - 如果我将一个类的默认构造函数声明为私有(private),为什么它不能被子类化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23662659/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com