In: Computer Science
Your output should be:
A Tale of Two Cities
Title: A Tale of Two Cities
Author: Charles Dickens
Rating: 4
Title: Foundation
Author: Isaac Asimov
Rating: 5
In case of any query do comment. Thanks
Code:
Book.java
//class Book
public class Book {
//a. private instance variable
private String title;
private String author;
private int rating;
//b. constructor with three parameters
public Book(String inTitle, String inAuthor, int inRating){
this.title = inTitle;
this.author = inAuthor;
this.rating = inRating;
}
//c. constructor with two parameters
public Book(String inTitle, String inAuthor){
this.title = inTitle;
this.author = inAuthor;
}
//d. method to return title
public String getTitle(){
return this.title;
}
//e. method to setRating
public void setRating(int inRating){
this.rating = inRating;
}
//f. toString to return string representation of an object
public String toString(){
return "Title: " + this.title + "\nAuthor: " + this.author + "\nRating: " + this.rating;
}
}
Lab3B.java
public class Lab3B
{
public static void main(String[] args) {
//a, declare an object book1
Book book1 = new Book("A Tale of Two Cities", "Charles Dickens", 4);
//b. create an object book2 with two parameter constructor
Book book2 = new Book ("Foundation", "Isaac Asimov");
//c. call setRating on book2 with value 5
book2.setRating(5);
//d. call getTitle on book 1 and print the return value
System.out.println(book1.getTitle());
//e.Use our toString shortcut to print all of book1’s information.
System.out.print(book1);
//f. Print a blank line.
System.out.println();
//g. Use the same coding to print all of book2’s info.
System.out.print(book2);
}
}
============screen shot of the code========
output: