Previous lesson 2/5 |home| Next lesson 4/5

Object-Oriented Programming Concept

Has-a Relationship

Last lesson, we learnt that OOP has two relationships. In this lesson, we will focus on has-a relationship, which is also called object composition.

Let's make a Pizza. Pizza is Mary's favorite food. Pizza can be designed as an object. Every Pizza has ingredients. Pizza has a topping. Pizza has sauce like tomato sauce. Do you pay attention to the boldfaced has? If Pizza is an object, topping is a member field of object Pizza. The relationship between Pizza and topping is "has-a" relationship. So does the sauce. "has-a" relationship in a object is called member field of an object.

Let's describe it in Java code.

 
public class Pizza {
    private int topping;//has-a relationship-->member field
    private String sauce;
    
    public int getTopping(){
        return topping;
    }
    
    public void setTopping(int howMany) {
        this.topping = howMany;
    }
    
    public String getSauce() {
        return sauce;
    }
    
    public void setSauce(String somesSauce) {
        this.sauce = someSauce;
    }
}

Assume that you understand Java basic code and be able to recognize that Pizza is an object and created in the standard Java coding convention.

Note that we don't create a constructor for the Pizza class, the compiler will create one called default constructor for you. The default constructor is a constructor without parameter list. We use getter/setter methods to make these states or fields accessible.

Previous lesson 2/5 |home| Next lesson 4/5