Saturday, November 16, 2013

Java Inheritance Example

Write Programs which models a library which contains many kinds of items:

Printed: books, journals, magazines, and documents
Multimedia: CDs, and DVDs.

Every item in the library must have an ID number and title. Every printed item must have a number of pages, and every multimedia item must have a length, in seconds. Define the classes Item, Printed, and Multimedia, making sure they have the appropriate relationships in the class hierarchy, and the appropriate private fields.
Create constructors for the three classes, using super() where necessary. Create toString() methods for each of the three classes. For an item, the string should have its id followed by its title. For printed and multimedia items, the id and title should be followed by the number of pages or running length with the appropriate unit (pages or seconds).

For example(Sample Output) :
7985 Alice in Wonderland (105 pages)
3565 In a Sentimental Mood (597 seconds)

Remember that the id and title fields in the Item class are private, so you'll need to call the toString() method belonging to the Item class for the other two toString() methods.


Solution:

 
public class InheritanceExample {
 
 public static void main(String args[]){
  //Creating objects
  Printed p1=new Printed(7895,"Alice in Wonderland",105);
  Multimedia m1=new Multimedia(3565,"In a Sentimental Mood",597);
  
  System.out.println(p1.toString());
  System.out.println(m1.toString());
 }
}

class Item {
 private int id;
 private String title;
 //Constructors
 public Item(){}
 public Item(int id,String title){
  this.id=id;
  this.title=title;
 }
 public int getId(){
  return id;
 }
 public String getTitle(){
  return title;
 }
 //Object string
 public String toString(){
  return String.format("%d %s", id,title);
 }
}

class Printed extends Item {
 private int noOfPages;
 //Constructors
 public Printed(){}
 public Printed(int id,String title,int page){
  super(id,title);
  noOfPages=page;
 }
 
 //To string
 public String toString(){
  return(String.format("%s (%d pages)",super.toString(),noOfPages));
 }
}

class Multimedia extends Item {
 private int length;
 //Constructors
 public Multimedia(){}
 public Multimedia(int id,String title,int time){
  super(id,title);
  length=time;
 }
 
 public String toString(){
  return(String.format("%s (%d seconds)",super.toString(),length));
 }
}

No comments:

Post a Comment