继承最佳实践Java

时间:2016-03-10 19:33:11

标签: java inheritance

假设我有一个父类Emitter,带有属性

private double launchAngle;
private double launchAngleVariation;

和构造函数

public Emitter(double launchAngle, double launchAngleVariation)
{ this.launchAngle = launchAngle;
  this.launchAngleVariation = launchAngleVariation;
}

和子类MobileEmitter,属性为

private int a;

和构造函数

public MobileEmitter(double launchAngle, int a)
{ super();   //how should this be handled?
  this.a = a;}

我的问题是处理超级电话的最佳方式是什么?

我应该在父类中创建一个空构造函数并使launchAngle受到保护,以便我可以直接在子构造函数中赋值吗?

或者更好的做法是在父类中创建一个单独的构造函数,只需将launchAngle作为参数,然后调用super(launchAngle)

1 个答案:

答案 0 :(得分:0)

namespace Example.Core.ViewModels
{
    public class RecyclerViewModel
        : MvxViewModel
    {
        private ListItem _selectedItem;

        public RecyclerViewModel()
        {
            Items = new ObservableCollection<ListItem> {
                new ListItem { Title = "A" },
                new ListItem { Title = "B" },
                new ListItem { Title = "C" },
                new ListItem { Title = "D" },
                new ListItem { Title = "E" }
            };
        }

        private ObservableCollection<ListItem> _items;

        public ObservableCollection<ListItem> Items
        {
            get { return _items; }
            set
            {
                _items = value;
                RaisePropertyChanged(() => Items);
            }
        }

        public ListItem SelectedItem
        {
            get { return _selectedItem; }
            set
            {
                _selectedItem = value;
                RaisePropertyChanged(() => SelectedItem);
            }
        }

        public virtual ICommand ItemSelected
        {
            get
            {
                return new MvxCommand<ListItem>(item =>
                {
                    SelectedItem = item;
                });
            }
        }

        private bool _isRefreshing;

        public virtual bool IsRefreshing
        {
            get { return _isRefreshing; }
            set
            {
                _isRefreshing = value;
                RaisePropertyChanged(() => IsRefreshing);
            }
        }

        public ICommand ReloadCommand
        {
            get
            {
                return new MvxCommand(async () =>
                {
                    IsRefreshing = true;

                    await ReloadData();

                    IsRefreshing = false;
                });
            }
        }

这是我认为你需要的。超级调用必须为其分配一些值。在您的情况下,您正在调用Emitter类(父类)中的默认构造函数。