Category Archives: oop

Java : OOP concepts applied

TextEntity.java

public interface TextEntity {
	public void print();
}

TextContainer.java

import java.util.List;

public abstract class TextContainer implements TextEntity {

	protected List<TextEntity> textEntities;
	protected String title;
	
	public void addEntity(TextEntity textEntity) {
		textEntities.add(textEntity);
	}

	public void print() {
		for(TextEntity textEntity : textEntities) {
			textEntity.print();
		}
	}
}

Book.java

import java.util.ArrayList;

public class Book extends TextContainer {

	public Book(String title) {
		this.title = title;
		this.textEntities = new ArrayList<TextEntity>();
	}
	
	public void print() {
		System.out.println("- Book : " + this.title);
		super.print();
	}

}

Chapter.java

import java.util.ArrayList;

public class Chapter extends TextContainer {
	
	public Chapter(String title) {
		this.title = title;
		this.textEntities = new ArrayList<TextEntity>();
	}
	
	public void print() {
		System.out.println("\tChapter : " + this.title);
		super.print();
	}
	
}

Section.java

import java.util.ArrayList;

public class Section extends TextContainer {

	public Section(String title) {
		this.title = title;
		this.textEntities = new ArrayList<TextEntity>();
	}

	public void print() {
		System.out.println("\t\tSection : " + this.title);
	}
	
}

Main.java

import java.util.List;
import java.util.ArrayList;

public class Main {
	public static void main(String[] args) {
		
		// Book 1 : Chapter 1
		TextContainer chapterA1 = new Chapter("1");		
		chapterA1.addEntity(new Section("A"));		
		chapterA1.addEntity(new Section("B"));
		// Book 1 : Chapter 2
		TextContainer chapterA2 = new Chapter("2");
		chapterA2.addEntity(new Section("A"));		
		chapterA2.addEntity(new Section("B"));		
		// Add chapters
		TextContainer bookA = new Book("ABC");
		bookA.addEntity(chapterA1);
		bookA.addEntity(chapterA2);
		
		// Book 2 : Chapter 1
		TextContainer chapterB1 = new Chapter("1");		
		chapterB1.addEntity(new Section("A"));		
		chapterB1.addEntity(new Section("B"));
		// Book 2 : Chapter 2
		TextContainer chapterB2 = new Chapter("1");		
		chapterB2.addEntity(new Section("A"));		
		chapterB2.addEntity(new Section("B"));
		// Add chapters
		TextContainer bookB = new Book("XYZ");
		bookB.addEntity(chapterB1);
		bookB.addEntity(chapterB2);

		List<TextContainer> bookList = new ArrayList<TextContainer>();		
		bookList.add(bookA);
		bookList.add(bookB);
		
		// Print
		for(TextContainer book : bookList) {
			book.print();
		}
	
	}
}	

run.bat

javac Main.java
java Main
pause
Advertisements
Tagged