(Has-A vs. Is-A) How do I host my program architecture? (JAVA)

I have three components:

  • Interface: Category
  • Parent class: MainCategory
  • Child class: SubCategory

I know that:

  • MainCategory IS-A Category
  • MainCategory Has-a SubCategory
  • SubCategory IS-A Category

However, when I try to structure them in my code with extendsand implements, I get a little confused. Here is what I still have, please let me know if this makes sense or if it needs to be done in some other way? Thanks.

public interface Category{}

public class MainCategory implements Category{}

public class SubCategory extends MainCategory implements Category {}

I want to know if I think about it correctly. Also, each MainCategorywill contain more than one SubCategory, is it right to use extendsor does this not mean aggregation? Thanks.

+4
source share
3 answers

, :

  • MainCategory IS-A
  • "-" ""
  • IS-A

SubCategory MainCategory. Category. SubCategory MainCategory, , , :

class Category {
    private List<SubCategory> children = new ArrayList<SubCategory>();

    public List<SubCategory> getSubCategories() {
        return children;
    }

    public void addSubCategory(SubCategory child) {
        child.setParent(this);
        children.add(child);
    }

    public Category getParent() {
        return null;
    }
}

class SubCategory extends Category {
    private Category parent = null;

    public Category getParent() {
        return parent;
    }

    public void setParent(Category parent) {
        this.parent = parent;
    }
}

Category SubCategory, SubCategory . , Category . , Category . SubCategory. SubCategory , SubCategory. , SubCategory, Category MainCategory, , .

, !

+1

MainCategory Has-A SubCategory , SubCategory MainCategory, . .

public class MainCategory implements Category{
      public SubCategory subcat = new SubCategory();
}

public class SubCategory implements Category{
}

SubCategory IS-A Category MainCategory IS-A Category, SubCategory MainCategory

+2

To get the following data:

MainCategory IS-A Category
MainCategory Has-A SubCategory
SubCategory IS-A Category

Do you want to:

// MC is a category and has a SC
public class MainCategory implements Category{
    // One or more SCs
    SubCategory sc1, sc2;
    ArrayList<SubCategory> scList;
    SubCategory [] scArray;
}

// SC is a category
public class SubCategory implements Category {}

You expand SubCategoryto MainCategoryif:

SubCategory IS-A MainCategory
+1
source

All Articles