For a project i am working with intherentance and an abstract class. with the help of a form i want to add items into a list, but get the following error during coding: cannot create an instance abstract type or interface 'Article'. does someone know how to fixt his?
articlemanager class:
private List<Article> items;
public ArticleManager()
{
items = new List<Article>();
}
public void addArticleEmergency(Article emergencyNews)
{
items.Add(emergencyNews);
}
abstract article class:
abstract class Article
{
public int id { get; private set; }
public string title { get; private set; }
public string text { get; private set; }
public Article(int id, string title, string text)
{
this.id = id;
this.title = title;
this.text = text;
}
public bool HasID(int id)
{
if (id == this.id)
{
return true;
}
return false;
}
public override string ToString()
{
return id ": \r\n" title " \r\n " text;
}
}
}
form:
private ArticleManager articalManagerAdd;
public Form1()
{
InitializeComponent();
this.articalManagerAdd = new ArticleManager();
}
private void btnMakeNewsArticle_Click(object sender, EventArgs e)
{
if(txtNewsNumber.Text == "" || txtNewsTitle.Text == "" || txtNewsText.Text == "" || !rbEmergency.Checked && !rbNormal.Checked )
{
lbSeeNewsItem.Items.Clear();
lbSeeNewsItem.Items.Add("Please fill in all the required information");
}
else
{
if (articalManagerAdd.GetArticle(Convert.ToInt32(txtNewsNumber.Text)) == null)
{
if (rbNormal.Checked)
{
articalManagerAdd.addArticleNormal(new Article(Convert.ToInt32(txtNewsNumber.Text), txtNewsTitle.Text, txtNewsText.Text));
MessageBox.Show("Normal news article has been added");
}
else if(rbEmergency.Checked)
{
Article emergencyNews = new NewsArticle(Convert.ToInt32(txtNewsNumber.Text), txtNewsTitle.Text, txtNewsText.Text);
MessageBox.Show("Emergency news article has been added");
}
}
else
{
lbSeeNewsItem.Items.Add("This id has already been used");
}
}
}
CodePudding user response:
As the comments have mentioned, you cannot create an instance of an abstract class.
So your code new Article(Convert.ToInt32(txtNewsNumber.Text), txtNewsTitle.Text, txtNewsText.Text))
will not compile.
You can inherit from a non-abstract class so your NewsArticle
class would be expected to work if you just removed the abstract
modifier to your Article
class.
Alternatively you could add a new sub-class of Article
say NormalArticle
and use that in your addArticleNormal
method