PublicationSystem.java
PublicationSystem.java
java
1 /* Problem Statement
2
3 In a publication system, Author a1 contributes to a set of books. Author a2 also contributes
to all the books contributed by a1 except for the second book, which a2 replaces with another
book. Write a program that defines two classes Author and PublicationSystem. Define a copy
constructor to create a2 from a1 such that changing the values of instance variables of
either a2 or a1 does not affect the other one. The program accepts name of author a2 and the
new book contributed by a2 as input.
4
5 Class Author has/should have the following members.
6
7 Private instance variables String name and String[] books to store author name and books
contributed respectively.
8 Define required constructor(s)
9 Accessor methods getName() and getBook(int) to get the author name and the book at a specific
index respectively.
10 Mutator methods setName(String) and setBook(int, String) to set the author name and the book
at a specific index respectively.
11 Class PublicationSystem has method main that does the following.
12
13 Two objects of Author a1 and a2 are created. a2 is created using a1.
14 name of Author a2 and second book contributed by a2 are updated by taking the input.
15 Finally, name of a1, a2 and second book contributed by a1 and a2 are printed.
16 What you have to do
17
18 Define a constructor to initialize the instance variables in class Author.
19 Define a copy constructor to create a deep copy of another Author object in class Author.
20 */
21
22
23
24 import java.util.*;
25
26 class Author {
27 private String name;
28 private String[] books;
29
30 // Define constructor to initialize instance variables
31 public Author(String name, String[] books) {
32 this.name = name;
33 this.books = new String[books.length]; // Create a new array to avoid aliasing
34 for (int i = 0; i < books.length; i++) {
35 this.books[i] = books[i];
36 }
37 }
38
39 // Define copy constructor to create a deep copy
40 public Author(Author other) {
41 this.name = other.name;
42 this.books = new String[other.books.length]; // Create a new array to avoid aliasing
43 for (int i = 0; i < other.books.length; i++) {
44 this.books[i] = other.books[i];
45 }
46 }
47
48 public void setName(String n) {
49 name = n;
50 }
51
52 public void setBook(int indx, String b) {
53 books[indx] = b;
54 }
55
56 public String getName() {
57 return name;
58 }
59
60 public String getBook(int indx) {
61 return books[indx];
62 }
63 }
64
65 public class PublicationSystem {
66 public static void main(String[] args) {
67 Scanner sc = new Scanner(System.in);
68 String[] books = {"Maths", "DL", "DSA", "DC"};
69 Author a1 = new Author("Nandu", books);
70
71 Author a2 = new Author(a1); // Using copy constructor
72 a2.setName(sc.next());
73 a2.setBook(1, sc.next());
74
75 System.out.println(a1.getName() + ": " + a1.getBook(1));
76 System.out.println(a2.getName() + ": " + a2.getBook(1));
77 }
78 }