开发者

Java; Accessing Member Instance Variables From Another Class

I have the following structure:

public class A {
     private javax.swing.JLabel fullName;

     public class B {
             public B() {
                    fullName.setText("Martha Stewart");
             }
     }
     ...
     ...
     ...
}

My goal is to have B (currently the sub class of A) to be in a separate class.

The problem is: When I separate the two classes, I lose functionality on the .setText() call for the JLabel. I realize that if B is in a separate class, I would have to write a public setter method in class A.

This, h开发者_JAVA技巧owever, is not plausible since I have about 100 buttons and use 4-5 different functions for each button. Creating a getter/setter method for each function is not plausible IMHO.

I'm trying to wrap my head around a better solution... can any of you help, friends?


B isn't a subclass of A. It's a nested (inner) class within A.

However, you shouldn't try to get access to fields of other types - it breaks encapsulation. Properties are a nicer solution - or alternatively, a setFullNameText method which calls fullName.setText() itself. Just because you have 100 buttons (ouch!) doesn't mean it's time to throw encapsulation out of the window. It does mean you might want to consider grouping those 100 fields into smaller classes though...


Don't let a class modify the attribute of another class, this breaks encapsulation. If you can't stand getters and setters, I'd suggest a configuration object (like a map), which could be given to the constructor and/or a setter of your main GUI class.

By the way:

I have about 100 buttons

I think it's a main issue. You should break your GUI in several classes representing groups of controls.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜