gpt4 book ai didi

java - 在 Java 中使用默认构造函数扩展类

转载 作者:行者123 更新时间:2023-12-01 06:11:37 24 4
gpt4 key购买 nike

我需要延长class A但它需要重写它的构造函数。

package com.example.io; // Package belongs to jar from maven dependency

public class A {
A(String s, Integer i) {
// constructor code
}

// other methods
}

由于它是默认构造函数(仅具有包访问权限的构造函数),我无法在包外部访问,因此我在源代码中创建了相同的包名称 com.example.io并扩展class A并构建成功。

package com.example.io; // Package belongs to my source code

public class B extends A{
B(String s, Integer i) {
super(s, i); // Throws error on runtime
}

// other methods
}

但它会抛出运行时错误 -

java.lang.IllegalAccessError: tried to access method com.example.io.A.<init>(Ljava/lang/String;Ljava/lang/Integer;)V from class com.example.io.B

如何解决这个问题?我的意思是,有什么方法可以使用默认构造函数扩展 A 类吗?

最佳答案

您绝对不应该只复制第 3 方库的包的名称。这可能会导致意想不到的结果。请参阅this answer .

相反,如果该类是public,则您应该创建自己的子类并定义自己的构造函数。如果父类(super class)的构造函数设置为 package,则无法调用它。在这种情况下,如果您有代码,您可以根据需要重新实现必要的构造函数操作:

public class MyClass extends A {

String myString;
Integer myInteger;
String myField;

MyClass(String s, Integer i) {
// Can't do this because it's set to package
// super(s, i);
// Re-implement?
this.myString = s;
this.myInteger = i;
// Implement your own stuff
this.myField = s + String.valueOf(i);
}
}

关于java - 在 Java 中使用默认构造函数扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33492150/

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