gpt4 book ai didi

java - 基 fragment 类中的共享变量是公共(public)的还是私有(private)的?

转载 作者:太空宇宙 更新时间:2023-11-04 11:40:12 25 4
gpt4 key购买 nike

我有一个基类 fragment (如下所示)。我在其他 3 个 fragment 类中扩展了此类,每个类都共享需要在这 3 个 fragment 中访问的相同 EditText。因此,我在基类中设置了 EditText 变量(因此我不必调用它 3 次,每个 fragment 调用一次)。

这个变量应该是public还是应该是private并且设置了getter方法?为什么?

这是我的基类 fragment :

public abstract class BaseFragment extends Fragment {
public EditText editText;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(getFragmentLayout(), container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);

editText = (EditText) view.findViewById(R.id.editText);
}

protected abstract int getFragmentLayout();
}

最佳答案

如果 editText 将由 BaseFragment 类的子类使用,那么您需要将其标记为 protected

Here是 javadoc,内容如下:

The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

通过这样做,子类将不需要使用 getterssetters 方法来访问此属性。他们将能够使用它,就好像它仅在这些类中定义一样。但是,对于任何不在 BaseFragment 包中或不扩展 BaseFragment 的类,此属性将为 private

关于java - 基 fragment 类中的共享变量是公共(public)的还是私有(private)的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42876989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com