2016-03-02 20 views
-1

中的方法中使用超类中的变量使用超类中的变量时遇到问题。请参阅下面的代码。在ConncetionMap(final int n)中,我可以成功使用超类中的变量n,但在重写的Test()方法中,变量n突然不再被识别。我该如何继续使用变量n?无法在子类

我认为如果ConncetionMap是公开的,我应该可以从同一个类的其他地方访问n。

public abstract class Connection { 
    public Connection(final int n) { 
    } 

    public abstract int Test(); 
} 


public class ConnectionMap extends Connection { 

    public ConnectionMap (final int n) { 
     super(n); 

     //Here, n is recognized from the superclass and it simply works 
     if (n < 0) { 
      throw new IllegalArgumentException("Error."); 
     } 
    } 

    @Override 
    public int Test() { 
     int c = n; //This is an example usage of n, and here n is not recognized anymore. 
    } 
} 

回答

1

n是构造函数的一个参数。像局部变量一样,参数的作用域是方法/构造函数。所以它只能从构造函数中看到。这与超类没有太大的关系,BTW。只是变量的范围。

如果超类没有提供任何方式来获取其值(例如,使用受保护或公开的getN()方法),则需要将其存储到子类中的字段中以便能够从另一个子类访问它方法:

public class ConnectionMap extends Connection { 

    private int n; 

    public ConnectionMap (final int n) { 
     super(n); 

     //Here, n is recognized from the superclass and it simply works 
     if (n < 0) { 
      throw new IllegalArgumentException("Error."); 
     } 
     this.n = n; 
    } 

    @Override 
    public int test() { 
     int c = this.n; 
     ... 
    } 
} 
+0

getN将是无用的,因为'n' **没有被记录下来,在Connection **的构造函数中丢弃了。 –

+0

您在父项中说“getN” –

+0

我假定发布的代码已被简化。我不明白为什么超类的构造函数会接受它根本不使用的参数。 test()方法也不能编译,但我也假设原因是OP删除了不相关的东西。 getN()方法返回传递给构造函数的n,它的作用与您在答案中添加的public n属性的作用相同。我不会建议使用公共属性BTW。 –

1

您已经声明n在你的构造函数的局部变量(参数),所以它不是可用的范围之外。试试这个:

public abstract class Connection { 
    public final int n; 
    public Connection(final int n) { 
     this.n = n; 
    } 

    public abstract int Test(); 
} 


public class ConnectionMap extends Connection { 

    public ConnectionMap (final int n) { 
     super(n); 

     //Here, n is recognized from the superclass and it simply works 
     if (n < 0) { 
      throw new IllegalArgumentException("Error."); 
     } 
    } 

    @Override 
    public int Test() { 
     int c = n; //This is an example usage of n, and here n is not recognized anymore. 
    } 
} 

这里,n在构造函数传递给n在你的对象。由于public> = protected,n从连接到ConnectionMap继承,所以它可以在Test()中使用。