简体   繁体   中英

“Variable might not have been initialized” only when multiple constructors are available

I have a class where I declare a variable and initialize it in the constructor. when I have one constructor in my code, everything works perfectly fine. The issue occurs when I add another constructor. Everything is the same in both constructors but only constructor's arguments are different. Any idea why this happens?

private final NavDrawerManager.OnDrawerItemClickListener mOnDrawerItemClickListener;
private final MoreMenuActivity.OnItemClickListener mOnItemClickListener;


public NavMenuAdapter(final List<NavMenuItem> menuItems, final String selectedId, final NavDrawerManager.OnDrawerItemClickListener onDrawerItemClickListener) {
    mMenuItems = menuItems;
    mSelectedId = selectedId;
    mOnDrawerItemClickListener = onDrawerItemClickListener;
}

public NavMenuAdapter(final List<NavMenuItem> menuItems, final String selectedId, final MoreMenuActivity.OnItemClickListener onItemClickListener) {
    mMenuItems = menuItems;
    mSelectedId = selectedId;
    mOnItemClickListener = onItemClickListener;
}

You are declaring attributes as final, but your constructors do not initialize them all.

private final NavDrawerManager.OnDrawerItemClickListener mOnDrawerItemClickListener;
private final MoreMenuActivity.OnItemClickListener mOnItemClickListener;

Each time an instance is constructed, it should have initialized all final attributes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM