Pascal Inheritance of a classes For Book Managaement - Computer Programming

Latest

C C++ Java Python Perl Programs Examples with Output -useful for Schools & College Students

Saturday, September 23, 2017

Pascal Inheritance of a classes For Book Managaement

Write an Program for Pascal Inheritance of a classes For Book Managaement

Program:
program inheritanceExample;

{$MODE OBJFPC} //directive to be used for creating classes
{$M+} //directive that allows class constructors and destructors

type
Books = Class
protected
title : String;
price: real;

public
constructor Create(t : String; p: real); //default constructor

procedure setTitle(t : String); //sets title for a book
function getTitle() : String; //retrieves title

procedure setPrice(p : real); //sets price for a book
function getPrice() : real; //retrieves price

procedure Display(); virtual; // display details of a book
end;
(* Creating a derived class *)

type
Novels = Class(Books)
private
author: String;

public
constructor Create(t: String); overload;
constructor Create(a: String; t: String; p: real); overload;

procedure setAuthor(a: String); // sets author for a book
function getAuthor(): String; // retrieves author name

procedure Display(); override;
end;
var
n1, n2: Novels;

//default constructor
constructor Books.Create(t : String; p: real);
begin
title := t;
price := p;
end;

procedure Books.setTitle(t : String); //sets title for a book
begin
title := t;
end;

function Books.getTitle() : String; //retrieves title
begin
getTitle := title;
end;

procedure Books.setPrice(p : real); //sets price for a book
begin
price := p;
end;

function Books.getPrice() : real; //retrieves price
begin
getPrice:= price;
end;

procedure Books.Display();
begin
writeln('Title: ', title);
writeln('Price: ', price);
end;

(* Now the derived class methods  *)
constructor Novels.Create(t: String);
begin
inherited Create(t, 0.0);
author:= ' ';
end;

constructor Novels.Create(a: String; t: String; p: real);
begin
inherited Create(t, p);
author:= a;
end;

procedure Novels.setAuthor(a : String); //sets author for a book
begin
author := a;
end;

function Novels.getAuthor() : String; //retrieves author
begin
getAuthor := author;
end;

procedure Novels.Display();
begin
writeln('Title: ', title);
writeln('Price: ', price:5:2);
writeln('Author: ', author);
end;

begin
n1 := Novels.Create('Gone with the Wind');
n2 := Novels.Create('Ayn Rand','Atlas Shrugged', 467.75);
n1.setAuthor('Margaret Mitchell');
n1.setPrice(375.99);
n1.Display;
n2.Display;
end.

Output:
Title: Gone with the Wind
Price: 375.99
Author: Margaret Mitchell
Title: Atlas Shrugged
Price: 467.75

Author: Ayn Rand

No comments:

Post a Comment