Friday, August 30, 2019

Composition or Has-A relationship in JAVA

Composition or Has-A relationship

          Composition is the design technique to implement has-a relationship in classes. We can use java inheritance or Object composition for code reuse. 

Java composition is achieved by using instance variables that refer to other objects. 



Program in JAVA:(taken simple example to explain composition)

package composition;

public class Book
{

private String title;
private int pages;
int count=0;
public Book(String title, int pages)
{
this.title=title;
this.pages=pages;
}
public void openBook()
{
System.out.println("book is opened start writing...");
}
public void turnPage()

count++;
if(count<=this.pages)
{
System.out.println("turning page...");
}
else
{
System.out.println("pages over...");
}
}
public void colseBook()
{
System.out.println("close the book...");
}
public void bookDetails()
{
                 System.out.println("The title of the book is "+this.title+" and it                               contains "+this.pages+" pages");
}
}
class Pen
{
private String colour;
public Pen(String colour)
{
this.colour=colour;
}
public void write()
{
System.out.println("write the content in the book with "+this.colour+" colour");
}
}
class Arthur
{
String name;
Book b;    //using class as a derived variables
Pen p;      //using class as a derived variables
public Arthur(String name,Book b,Pen p)
{
this.name=name;
this.b=b;
this.p=p;
}
public void writeContent()
{
b.openBook();
b.turnPage();
p.write();
b.colseBook();
}
public void bookDetails()
{
b.bookDetails();
}
}
class Main
{
public static void main(String [] args)
{
Arthur a=new Arthur("kookie",new Book("BTS",29),new Pen("Black"));
a.writeContent();
a.bookDetails();
}
}

No comments:

Post a Comment