Skip to content

Latest commit

 

History

History
80 lines (54 loc) · 1.98 KB

ex5-3.md

File metadata and controls

80 lines (54 loc) · 1.98 KB

5.3 Adding Class Inheritance

Example

The Media class has three properties: title, type, and mediaTitle. The title property is a string that stores the title of the media. The type property is a string that stores the type of the media. The mediaTitle property is a getter and setter for the title property.

The Book class extends the Media class and adds two properties: author and isbn. The author property is a string that stores the author of the book. The isbn property is a string that stores the ISBN of the book.

The main() function creates two instances of the Media class: myMedia and myBook. The myMedia instance is assigned the title "Tron". The myBook instance is assigned the title "Jungle Book" and the author "R Kipling".

The print() statements then print the title, author, and type of each media instance to the console.

class Media {
  String title = "";
  String type = "";

  Media(){ type = "Class"; }

  void setMediaTitle(String mediaTitle){ title = mediaTitle; }

  String getMediaTitle(){ return title; }

  String getMediaType(){ return type; }
}

class Book extends Media {
  String author = "";
  String isbn = "";

  Book(){ type = "Subclass"; }

  void setBookTitle(String bookTitle){ title = bookTitle; }

  void setBookAuthor(String bookAuthor){ author = bookAuthor; }

  void setBookISBN(String bookISBN){ isbn = bookISBN; }

  String getBookTitle(){ return title; }

  String getBookAuthor(){ return author; }

  String getBookISBN(){ return isbn; }
}

void main() {
  var myMedia = Media();

  myMedia.setMediaTitle('Tron');
  print ('Title: ${myMedia.getMediaTitle()}');
  print ('Type: ${myMedia.getMediaType()}');


  var myBook = Book();
  myBook.setBookTitle("Jungle Book");
  myBook.setBookAuthor("R Kipling");
  print ('Title: ${myBook.getMediaTitle()}');
  print ('Author: ${myBook.getBookAuthor()}');
  print ('Type: ${myBook.getMediaType()}');
}

Example Output:

Title: Tron
Type: Class
Title: Jungle Book
Author: R Kipling
Type: Subclass