如何拦截超类构造函数参数?
在电话面试期间,我被问到以下问题:
给定以下类定义:
public class ClassA {
public ClassA(int x) {
// do some calculationand initialize the state
}
}
及其使用随机整数生成器初始化超类的子类。
public class ClassB extends ClassA {
public ClassB() {
super(StaticUtilityClass.someRandomIntegerValGenerator())
}
}
您需要截取 x 的值(由 someRandomIntegerValGenerator 生成的随机 int)并将其存储在 ClassB 成员中。 A 类不能更改。 我最终不知道如何做到这一点,因为 ClassB 构造函数内的第一个调用需要是对 super() 的调用。在调用 super() 之前,ClassB 没有状态,并且 someRandomIntegerValGenerator 生成的值无法分配给任何 ClassB 成员。我唯一的方向是使用 线程局部 但我认为这应该是一些更简单的解决方案。
有什么想法吗?
I was asked the following question during phone interview I had:
Given the following class definition:
public class ClassA {
public ClassA(int x) {
// do some calculationand initialize the state
}
}
and its child class that initializes a super class using a random integer generator.
public class ClassB extends ClassA {
public ClassB() {
super(StaticUtilityClass.someRandomIntegerValGenerator())
}
}
you need to intercept the value of x (the random int produced by someRandomIntegerValGenerator) and store it in ClassB member. ClassA can not be changed.
I ended up with no idea how this can be done because the first call inside the ClassB constructor needs to be the call to super(). Untill the super() was called there is no state for ClassB and the value produced by the someRandomIntegerValGenerator can not be assigned to no ClassB member. The only direction I had was using a
ThreadLocal
but I think it should be some easier solution.
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这个怎么样:
How about this: