Have a Question?

If you have any question you can ask below or enter what you are looking for!

Difference between IS-A relationship and Has-A relationship.

Difference between IS-A relationship and Has-A relationship.
Difference between IS-A relationship and Has-A relationship.
package com.java4us;

public class Bike {
    private String color;
    private int maxSpeed;

    public void bikeInfo() {
        System.out.println("Bike Color= " + color + " Max Speed= " + maxSpeed);
    }

    public void setColor(String color) {
        this.color = color;
    }

    public void setMaxSpeed(int maxSpeed) {
        this.maxSpeed = maxSpeed;
    }
}

In the code above the Bike class has a few instance variables and methods.

package com.java4us;

public class Avanger extends Bike {

    public void AvangerStart() {
        Engine PulsarEngine = new Engine();
        PulsarEngine.stop();
    }
}

Avenger is a type of bike that extends the Bike class that shows that Avenger is a Bike. Pulsar also uses an Engine’s method, stop, using composition. So it shows that a Avenger has an Engine.

package com.java4us;

public class Engine {
    public void start() {
        System.out.println("Started:");
    }

    public void stop() {
        System.out.println("Stopped:");
    }

}

The Engine class has the two methods start( ) and stop( ) that are used by the Avenger class.

package com.java4us;

class Test {
    public static void main(String[] args) {
        Avanger myAvanager = new Avanger();
        myAvanager.setColor("BLACK");
        myAvanager.setMaxSpeed(136);
        myAvanager.bikeInfo();
        myAvanager.AvangerStart();
    }

}

In the code above we make an object of the Avenger class and then initialize it. All the methods like setColor( ), bikeInfo( ), setMaxSpeed( ) are used here because of the Is-A relationship of the Avenger class with the Bike class.

Leave a Reply

Your email address will not be published. Required fields are marked *