gpt4 book ai didi

java - 如何为子类创建构造函数

转载 作者:行者123 更新时间:2023-12-01 17:41:52 24 4
gpt4 key购买 nike

import java.util.*;

class A {

protected int n;

public A(int a) {
n = a;
}

protected int disp() {
return n;
}
}

class B extends A {

// what should i do here
}

public class Hello {

public static void main(String[] args) {
//Your Code Here
int a =5;
A obj= new B(a);
System.out.print(obj.disp());
}
}

最佳答案

重要的是A使用其构造函数之一进行初始化。子类 B 中的构造函数没有必要匹配 A 中构造函数的参数。因此,您可以在子类 B 中定义任何构造函数。但请确保您调用super( <some int> )在那。

例如,即使是以下内容也可以。

class B extends A {
public B(){ //Default constructor
super( 1 );
}
}

另外,

  1. 如果子类中有多个构造函数B ,那么他们每个人都必须调用super( <some int> ) .
  2. 如果父类中有多个构造函数A ,然后在子类构造函数中,通过 super( <params> ) 调用其中任意一个就可以了。

关于java - 如何为子类创建构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60134675/

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