Suppose You are given a UML design of the Author and Book like below:
A class called Author
is designed as shown in the class diagram. It contains:
- Three
private
member variables:name
(String
),email
(String
), andgender
(char
of either'm'
or'f'
- you might also use aboolean
variable calledisMale
having value oftrue
orfalse
). - A constructor to initialize the
name
,email
andgender
with the given values.
(There is no default constructor, as there is no default value forname
,email
andgender
.) - Public getters/setters:
getName()
,getEmail()
,setEmail()
, andgetGender()
.
(There are no setters forname
andgender
, as these properties are not designed to be changed.) - A
toString()
a method that returns "name (gender) at email
", e.g., "Tan Ah Teck (m) at ahTeck@somewhere.com
".
Let's design a Book
class. Assume that a book is written by one (and exactly one) author. The Book class (as shown in the class diagram) contains the following members:
- Four
private
member variables:name
(String
),author
(an instance of theAuthor
the class we have just created, assuming that each book has exactly one author),price
(double
), andqty
(int
). - The
public
getters and setters:getName()
,getAuthor()
,getPrice()
,setPrice()
,getQty()
,setQty()
. - A
toString()
that returns "'book-name' by author-name (gender) at email
". You could reuse theAuthor
'stoString()
method, which returns "author-name (gender) at email
".
#Solution:
#Author.java:
package MorePractice;
public class Author {
private String name,email;
private char gender;
Author(String name, String email, char gender){
this.name = name;
this.email = email;
this.gender = gender;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public char getGender() {
return gender;
}
public String toString(){
return name+" ("+gender+") at "+email;
}
}
#Book.java:package MorePractice;
public class Book {
private String name;
private Author author;
double price;
int qty;
Book(String name, Author author, double price, int qty){
this.name = name;
this.author = author;
this.price = price;
this.qty = qty;
}
public String getName() {
return name;
}
public Author getAuthor() {
return author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String toString(){
return "'"+name+"' by author-"+author;
}
}
#BookMain.java:package MorePractice;
public class BookMain {
public static void main(String[] args) {
Author a1 = new Author("Humayun Ahmed","himu@humayun.com",'m');
//System.out.println(a1);
Book b1 = new Book("Aj Himur Biye",a1,150.00,5);
System.out.println(b1);
}
}