Monday 24 August 2015

Java Tutorial : Inheritance Has A Relationship (Car)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=lQlu0kel2x8&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge
Java Tutorial : Inheritance Has A Relationship (Car)
Java Tutorial : Inheritance Has A Relationship (Car)
Car.java
public class Car
{

    private String color;
    private int maxSpeed;

    public Car(String color, int maxSpeed)
    {
        super();
        this.color = color;
        this.maxSpeed = maxSpeed;
    }

    public String getColor()
    {
        return color;
    }

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

    public int getMaxSpeed()
    {
        return maxSpeed;
    }

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

    public void carInfo()
    {

        System.out.println("Car Color= " + color + ", Max Speed= " + maxSpeed);

    }
}
Engine.java
public class Engine
{
    public void start()
    {

        System.out.println("Engine Started:");

    }

    public void stop()
    {

        System.out.println("Engine Stopped:");

    }
}
MarutiSwift.java
/**
 * 
 * MarutiSwift is specific type of Car which extends Car class means MarutiSwift
 * IS-A Car.
 * 
 * MarutiSwift extends Car and thus inherits all properties and methods from Car
 * (except final and static).
 * 
 * MarutiSwift can also define all its specific functionality.
 */
public class MarutiSwift extends Car
{
    /*
     * MarutiSwift HAS-A Engine
     */
    private Engine engine;

    public MarutiSwift(String color, int maxSpeed, Engine engine)
    {
        super(color, maxSpeed);
        this.engine = engine;
    }

    public void startMarutiSwift()
    {
        engine.start();
    }

}
RelationshipDemo.java
/**
 * RelationsDemo class is making object of MarutiSwift class and initialized it.
 * Though MarutiSwift class does not have setColor(), setMaxSpeed() and carInfo()
 * methods still we can use it due to IS-A relationship of MarutiSwift class with Car
 * class.
 */

public class RelationshipDemo
{

    public static void main(String[] args)
    {

        Engine engine = new Engine();
        MarutiSwift marutiSwift = new MarutiSwift("Red", 200, engine);
        marutiSwift.carInfo();
        marutiSwift.startMarutiSwift();
    }
}

Output
Car Color= Red, Max Speed= 200
Engine Started:
To Download InheritanceDemo-HAS-A-CarApp Project Click the below link
https://sites.google.com/site/javaee4321/java/InheritanceDemo-HAS-A-CarApp.zip?attredirects=0&d=1

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment