我有一些像这样的代码结构:
public class Mainframe{
private Object o;
public Mainframe (Object o){
this.o = o;
}
void xy(){
new Newclass(this);
}
}
public class Newclass{
Mainframe frame;
public Newclass(Mainframe frame){
this.frame = frame;
}
}
在Newclass中,如何在不更改构造函数的情况下使用Object o?这可能吗?
答案 0 :(得分:0)
没有。私人意味着私人。 私有存在的原因是为了防止您询问是否可以执行此操作。如果您想这样做,那么您不需要使用私有,因为它没有其他目的,但阻止您这样做。
另一个解决方案是保持Object o private,但在Mainframe类中添加 accessor :
public class Mainframe{
private Object o;
public Mainframe(Object o) {
this.o = o;
}
void xy() {
new Newclass(this);
}
public getO() {
return o;
}
}
-
public class Newclass{
Mainframe frame;
public Newclass(Mainframe frame){
this.frame = frame;
}
public void printMainframeO() {
System.out.println(frame.getO());
}
}