129k views
1 vote
Write a class named Book containing: Two instance variables named title and author of type String. A constructor that accepts two String parameters. The value of the first is used to initialize the value of title and the value of the second is used to initialize author. A method named toString that accepts no parameters. toString returns a String consisting of the value of title, followed by a newline character, followed by the value of author.

1 Answer

2 votes

Answer:

The code to this question can be given as:

Code:

public class Book //define class.

{

private String title, author; //define variable.

Book(String a, String b) //define parameterized constructor.

{

title = a; //holding value.

author = b;

}

public String toString() //string function

{

return title + "\\" + author; //return value.

}

}

Explanation:

In the above java code firstly we declare the class book that name is already given in the question. Then we declare the private variable that datatype is string author and title. Then we declare the parameterized constructor. In the parameterized constructor we use the private variable for hold constructor parameter value. Then we declare the tostring() function in this function we return value of the title and author variable.