java调用其他类的变量,从Java中的其他类访问私有变量

i hope that i mean my words.

i have a class like this:

public class MainClass extends JFrame{

private JLabel mainlabel;

private SampleClass sample=new SampleCalss();

public void intital(){

mainlabel=new JLabel("Main");

sample.setMethod(getLabel());

//

//some code

//

add(mainlabel);

}

public static void main(){

intital();

}

public JLabel getLabel(){

return mainlabel;

}

}

and other class like this:

public class SampleClass extends JFrame{

private JButton button=new JButton("Change");

private JLabel sLabel;

public SampleClass(){

//somecode

//

button.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

sLabel.setText("Sample text set");

}

});

add(jButton);

}

public void setMethod(JLabbel l){

sLabel=l;

}

}

is this a true way to access mainlabel and change its value from other class(in this sample code in class SampleClass) is there a better or right solution?

note that MainClass is class that has main method.

解决方案

The correct way to access a private variable from another class is with getter and setter methods. Otherwise, you should have made that variable public.

That is:

// getter

public JLabel getMainLabel() {

return mainlabel;

}

// setter

public void setMainLabel(JLabel mainLabel) {

this.mainlabel = mainLabel;

}

However, it is a bad practice to return private data directly - that allows external code to modify your private state. In general, you should return a copy of your private data so that external code can't mess with the internals of your class. But if you need external code to call methods on your private data, then you should probably be providing manipulation methods in your class, rather than directly exposing private data.

You probably really want to create methods like setText() and getText() in your main class, and then call the setText() and getText() methods on mainlabel. However, you need to be careful with this, as you might be inclined to replicate every single method defined by JLabel in your class. That would tightly couple both your class and its consumers wit the JLabel implementation. If you choose to replace the JLabel with something else in the future, it will take a lot of work to unwind the coupling you've created.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值