Java 唐’;t从超类构造函数调用子类方法
考虑以下代码Java 唐’;t从超类构造函数调用子类方法,java,Java,考虑以下代码 /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package example0; /** * * @author yccheok */ public class Main { static class A { private final String var; public A
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package example0;
/**
*
* @author yccheok
*/
public class Main {
static class A {
private final String var;
public A() {
var = getVar();
// Null Pointer Exception.
System.out.println("var string length is " + var.length());
}
public String getVar() {
return "String from A";
}
}
static class B extends A {
private final String bString;
// Before B ever constructed, A constructor will be called.
// A is invoking a overriden getVar, which is trying to return
// an initialized bString.
public B() {
bString = "String from B";
}
@Override
public String getVar() {
return bString;
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
B b = new B();
}
}
目前,在我看来,有两种方法可以避免这样的问题
要么让这门课成为最后一门课
static final class A {
private final String var;
public A() {
var = getVar();
// Null Pointer Exception.
System.out.println("var string length is " + var.length());
}
public String getVar() {
return "String from A";
}
}
或
使getVar方法成为最终方法
static class A {
private final String var;
public A() {
var = getVar();
// Null Pointer Exception.
System.out.println("var string length is " + var.length());
}
public final String getVar() {
return "String from A";
}
}
作者试图提出预防上述问题的方法。然而,解决方案似乎很麻烦,因为需要遵循一些规则
除了制定最终的和作者建议的方法外,还有其他方法可以防止上述问题(不要从超类构造函数调用子类方法)发生吗
使getVar方法成为最终方法
static class A {
private final String var;
public A() {
var = getVar();
// Null Pointer Exception.
System.out.println("var string length is " + var.length());
}
public final String getVar() {
return "String from A";
}
}
这绝对是你需要做的
如果您依赖于方法的功能来初始化对象,那么不应该让子类破坏该方法
回答您的问题,另一种防止它的方法是在A
中将getVar
设为私有
请参阅代码的简化版本:
// A.java
class A {
private final String var;
public A(){
var = getVar();
var.length();
}
private String getVar(){
return "This is the value";
}
}
class B extends A {
private final String other;
public B(){
other = "Other string";
}
public String getVar(){
return other;
}
}
class Main{
public static void main( String [] args ) {
new B();
}
}
顺便说一句,为什么把它们作为静态嵌套类,只是为了制造混乱 到底是什么问题?嗯,是什么问题?所有这些行为看起来都是完全正确的。是的,存在null指针异常,但这只是因为您有一个返回null的方法。这是很合理的。你想要什么样的行为?如果B还没有定义一个变量,您是否希望使用A变量?B可以自己做。用这段代码你到底想实现什么?如果我们不知道您到底想做什么,就很难提出任何建议。以后请不要在代码内部包含问题或错误消息,而是在代码外部包含问题或错误消息。>>静态嵌套类抱歉。它们不应该是静态的。我只想从static main打个电话。