如何使用在构造函数中实例化的超级(变量)?
How to use a super(variable) instantiated in constructor?
大家好Whosebug,
我不确定我的问题是否多余。但是,在 constructor 中使用 super() 实例化 variable 之后,您将如何使用 super(variable) 在另一个相同的方法中class。我在某处读到,如果您在父 class 中使用“protected”,您应该可以访问它,但我希望避免这样做。
示例:
public class test extends trial{
public test (trial variable){
super(variable);
}
public double testMethod(){
return [super(variable)]; //This is where the super(variable) is going
}
}
我觉得Trail
有点像:
public class Trial {
private final Trial variable;
public Trail(Trial variable) {
this.variable = variable;
}
}
如果是这种情况,则 Test
无法访问 super.variable
,除非将 variable
的 access control 更改为受保护(或更高)或具有受保护(或更高) ) getter 对于 variable
。没有其他办法绕过这个(1)。
after instantiating a variable using super() in a constructor
您不是(直接)实例化变量,而是在 Trial
上调用构造函数。然后 Trial
中的构造函数正在实例化变量。
1) 你可以用邪恶的 hackory 来解决这个问题。然而,这样做在 99% 的情况下都是错误的。
您所做的不是初始化变量,而是调用父构造函数,即 trial 的构造函数。
如果超级变量受到保护或 public,则可以直接从子 class 访问它们。
例如
public class A{
public int foo;
protected int foo2;
private int foo3;
}
public class B extends A{
public void someMethod()
{
foo=1;
foo2=3;
//foo3 cant be accessed because it is private. only and only class A can
//access it.
}
}
如果您的超类不公开您作为构造函数参数接收的内容并传递给超类构造函数,您始终可以让子类自己引用它:
public class Test extends Trial {
private Trial variable;
public Test(Trial variable) {
super(variable);
this.variable = variable;
}
public void testMethod() {
this.variable.doWhatever();
}
}
大家好Whosebug,
我不确定我的问题是否多余。但是,在 constructor 中使用 super() 实例化 variable 之后,您将如何使用 super(variable) 在另一个相同的方法中class。我在某处读到,如果您在父 class 中使用“protected”,您应该可以访问它,但我希望避免这样做。
示例:
public class test extends trial{
public test (trial variable){
super(variable);
}
public double testMethod(){
return [super(variable)]; //This is where the super(variable) is going
}
}
我觉得Trail
有点像:
public class Trial {
private final Trial variable;
public Trail(Trial variable) {
this.variable = variable;
}
}
如果是这种情况,则 Test
无法访问 super.variable
,除非将 variable
的 access control 更改为受保护(或更高)或具有受保护(或更高) ) getter 对于 variable
。没有其他办法绕过这个(1)。
after instantiating a variable using super() in a constructor
您不是(直接)实例化变量,而是在 Trial
上调用构造函数。然后 Trial
中的构造函数正在实例化变量。
1) 你可以用邪恶的 hackory 来解决这个问题。然而,这样做在 99% 的情况下都是错误的。
您所做的不是初始化变量,而是调用父构造函数,即 trial 的构造函数。 如果超级变量受到保护或 public,则可以直接从子 class 访问它们。 例如
public class A{
public int foo;
protected int foo2;
private int foo3;
}
public class B extends A{
public void someMethod()
{
foo=1;
foo2=3;
//foo3 cant be accessed because it is private. only and only class A can
//access it.
}
}
如果您的超类不公开您作为构造函数参数接收的内容并传递给超类构造函数,您始终可以让子类自己引用它:
public class Test extends Trial {
private Trial variable;
public Test(Trial variable) {
super(variable);
this.variable = variable;
}
public void testMethod() {
this.variable.doWhatever();
}
}