Store String of one class into an object of another class - java

I am working on a project that links books to their authors.The author info is part of the book class and it is an Author object in the book class and its data will become part of the book class. I have the author class:
public class Author {
private String Name;
private String email;
private char gender;
public Author( ) {
Name="Emily";
email="email#email.com";
gender='f';
}
public String getName (){
return Name;
}
public void setName (String Name){
this.Name=Name;
}
public String getEmail (){
return email;
}
public void setEmail(String email){
this.email=email;
}
public char getGender (){
return gender;
}
public void setGender(char gender){
this.gender=gender;
}
public String toString () {
String x = "Name: " + Name + "email " + "gender: " + gender;
return x;
}
}
and the book class:
public class Book {
private String name;
private Author author;
private double price;
private int quantity;
public Book (){
name="Book Name";
author=Author.toString();
price=11.79;
quantity=2;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Author getAuthor(){
return author;
}
public void setAuthor () {
this.author=author;
}
public double getPrice () {
return price;
}
public void setPrice (double price) {
this.price=price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity (int quantity) {
this.quantity=quantity;
}
public String toString (){
String x = "Book is " + name + "Author and author info "+ author + "Price " + price + "Quantity " + quantity;
return x;
}
}
I need to store the contents of the toString() method in the Author variable in the book class as the author info. How do I do this?

You don't need to store the value of the toString() method of the Author class, this would couple your classes unnecessarily and break one of the core principals of good OO design.
The toString method of the Author class should be responsible for presenting a sensible String representation of its state (which it seems to). Your book class should do the same, delegating to classes it interacts with to do the same:
public String toString() {
return "Book is " + name + "Author and author info "+ author.toString() + "Price " + price + "Quantity " + quantity;
}
As noted in the comments, you're already doing this in the code snippet posted in the question, your question implies that this this may have not been 'by design'. I would recommend researching Object Encapsulation and delegation.

Related

How to write an array of objects through composition in another object and how to create them in main class?

For example, there is this program where I could write in the Book object (constructor) many Authors. The errors appear only in main, but there may be some code in other classes, which should be written differently.
```
package ex1;
public class Author {
private String name, email;
private char gender;
public Author(String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public char getGender() {
return gender;
}
}
```
In the photo, you can see the program requirements.
```
package ex1;
import java.util.Arrays;
public class Book {
private String name;
private Author[] authors;
private Page page;
private double price;
private int qty = 1;
public Book(String name, Author[] authors, double price) {
this.name = name;
this.authors = authors;
this.price = price;
}
public Book(String name, Author[] authors, Page page, double price, int qty) {
this.name = name;
this.authors = authors;
this.price = price;
this.qty = qty;
this.page = page;
}
#Override
public String toString() {
return "Book [name=" + name + ", authors=" + Arrays.toString(authors) + ", page=" + page + ",
price=" + price + ", qty=" + qty + "]";
}
public String getName() {
return name;
}
public Author[] getAuthors() {
return authors;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
//....
}
```
The class page is working at least.
```
package ex1;
public class Page {
private int pageNumber, numberOfWords;
private String footnote;
public Page(int pageNumber, int numberOfWords, String footnote) {
this.pageNumber = pageNumber;
this.numberOfWords = numberOfWords;
this.footnote = footnote;
}
#Override
public String toString() {
return "Page [pageNumber=" + pageNumber + ", numberOfWords=" + numberOfWords + ", footnote=" +
footnote + "]";
}
public int getPNr() {
return pageNumber;
}
public int getWords() {
return numberOfWords;
}
public String getFoot() {
return footnote;
}
}
```
So here I would like to see that I could create a Book like this or in a similar manner:
Book b2 = new Book("Ac2", authors[authorAna, Kratos], 35);
```
package ex1;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Author authors[] = new Author[2]; // this is a method but it doesn't work as intended
Author authorAna = new Author("Ana", "A#em.com", 'f');
Author Kratos = new Author("Kratos", "K#em.com", 'm');
authors[0] = authorAna;
authors[1] = Kratos;
Page p6 = new Page(6, 400, "He jumped into the haystack to hide from enemies");
Book b1 = new Book("Ac1", authors, 25);
//Book b2 = new Book("Ac2", authorAna, 35);
//Book b3 = new Book("God of War1", Kratos, 20);
//Book b4 = new Book("GoW2", , p6, 20, 40);
System.out.println(Kratos + "\n" + b1.toString());
//System.out.println(b2);
//System.out.println(b3);
//System.out.println(b4);
}
}
```
You can create the Author array like this. Then you would need to index the array to get the individual author object.
Author[] authors = {new Author("Ana", "A#em.com", 'f'),
new Author("Kratos", "K#em.com", 'm')};
Book b1 = new Book("Ac1", authors, 25);
If need be, you could then create a book array the same way or create a book builder.
class Book {
private String name;
private Author[] authors;
private Page page;
private double price;
private int qty = 1;
private Book() {
}
public Book(String name, Author[] authors, double price) {
this.name = name;
this.authors = authors;
this.price = price;
}
public Book(String name, Author[] authors, Page page,
double price, int qty) {
this.name = name;
this.authors = authors;
this.price = price;
this.qty = qty;
this.page = page;
}
#Override
public String toString() {
return "Book [name=" + name + ", authors="
+ Arrays.toString(authors) + ", page=" + page
+ ", price=" + price + ", qty=" + qty + "]";
}
public String getName() {
return name;
}
public Author[] getAuthors() {
return authors;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static Book bookBuilder() {
return new Book();
}
public Book price(double price) {
setPrice(price);
return this;
}
public Book quantity(int quantity) {
qty = quantity;
return this;
}
public Book name(String name) {
this.name = name;
return this;
}
}
It would be used like this.
Book b = Book.bookBuilder().name("Ac2").price(40.).quantity(20);
Note that you can modify the bookBuilder method to accept any elements of the book class that would always be required. Then you can add whatever methods you need. And the other nice feature of builders is that the order you call the methods doesn't matter (except for the first one of course).

How to convert object value into string containing multiple data in objects?

class Author
{
String name;
String email;
char gender;
Author(String name,String email,char gender)
{
this.name = name;
this.email = email;
this.gender = gender;
}
}
class Book
{
String name;
Author author;
double price;
int qtyInStock;
Book(String name,Author author,double price,int qtyInStock)
{
this.name = name;
this.author = author;
this.price = price;
this.qtyInStock = qtyInStock;
}
void setName(String name)
{
this.name = name;
}
void setAuthor(Author author)
{
this.author = author;
}
void setPrice(double price)
{
this.price = price;
}
void setQtyInStock(int qtyInStock)
{
this.qtyInStock = qtyInStock;
}
String getName()
{
return name;
}
Author getAuthor()
{
return author;
}
double getPrice()
{
return price;
}
int getQtyInStock()
{
return qtyInStock;
}
}
public class HOA1
{
public static void main(String[] args)
{
Author author = new Author("Javed","javedansarirnc#gmail.com",'M');
Book book = new Book("WiproS",author,500.99,3);
book.setName("JavaWorld");
System.out.println(book.getName());
String[] authDetails = book.getAuthor().toString();
for(String strr: authDetails)
{
System.out.println(strr);
}
}
}
In the above code, I have to provide solution for the question stated as "Create a class Author with the following information.
Member variables : name (String), email (String), and gender (char)
Parameterized Constructor: To initialize the variables
Create a class Book with the following information.
Member variables : name (String), author (of the class Author you have just created), price (double), and qtyInStock (int)
[Assumption: Each book will be written by exactly one Author]
Parameterized Constructor: To initialize the variables
Getters and Setters for all the member variables
In the main method, create a book object and print all details of the book (including the author details) "
I am not able to solve it !
I want to print author details using book object .Please help.
First, you need to override the toString() method in your Author class, to pretty print the fields. An example could be:
class Author {
// ... your fields ...
#Override
public String toString() {
return "Author{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
'}';
}
}
Then, here's the mistake that you are making.
The toString() method from the Author class returns a String, not an array of String (String[] as you did). So, you could just do:
String authDetails = book.getAuthor().toString();
System.out.println(authDetails);
But, the recommended way to do this is the following. Just use an object for the Author class, and pass that object to the System.out.println(...) method. This will automatically call the toString() method on the given object.
Author author = book.getAuthor();
System.out.println(author);
Has the same effect as:
System.out.println(author.toString());
Override the toString() method in your Author class. See below the code
class Author {
// ... your fields ...
#Override
public String toString() {
return "Author{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
'}';
}
Once toString method is defined in Author class you can print the Author class all objects data using either toString method or when you print the Author instance as well.
System.out.println("Author data:"+book.getAuthor());
The toString() method returns the string representation of the object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc.

how to store object in array where i want to declare 2 or more object and how to call that array using anther class object

this is main method
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
now i created 2nd class authoer with getter and setter
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
noow i created new class Book
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
when i run this program the output give the memory adress ho can i print theese detail
You need to override toString() method in the class Author.
For example:
#Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
When you pass as argument of the method System.out.println() name of variable, method toString() of the class of that variable is being called. If you don't override that method in class Author or Book, toString() method inherited by these classes from Object class is being called (all classes in Java inherit from Object class). By default, this method prints address in memory for classes with toString() not defined in their bodies. There is a simple example, how you can override it in Author method:
class Author {
#Override
public String toString() {
return "Author name: " + this.name + "\nAuthor email: " + this.email + "\nAuthor gender : " + this.gender;
}
To print contents of an array (in your example to print each Author contained in Author[] authors) you might want to use one of these way to achieve that (as Author[] or Book[] is actually a type of array and not a type of Book or Author and has its own toString() method printing address in memory) :
Create a loop iterating over each element of authors array:
for (Author author : authors) {
System.out.println(author + "------"); // toString() method of each Author is called and added simple separator
}
Call Arrays.toString(authors) method. Class Arrays is provided to let you manipulate arrays in many different ways. You can read about this class in Java API documentation. This is a part of what documentation says about Arrays.toString() method:
Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
package oops;
public class Main {
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
}
}
package oops;
public class Author {
private String name;
private String email;
private String gender;
public Author (String name,String email, String 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 String toString() {
return name+ " " +email+ " " +gender+ " ";
}
package oops;
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
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 getName() {
return name;
}
/*public Author[] getAuthor() {
return author;
} */
public Author[] getAuther() {
for (int i=0;i<=author.length;i++);
return author;
}
public String toString() {
return name+" "+author+" "+price+" "+qty+" ";
}
public Author[] getAutherNames() {
for (int i=0;i<=author.length;i++);
return author;
}
}
this is my full program
You an override toString() or you can print the attributes of the object directly as follows:
Book b = new Book(/*args*/);
System.out.println("Name: " + b.name);
// continue printing all the attributes in the same way
You can try this instead of overriding toString() method in the object class.
Hope this helps...

Two classes making same instance?? java

so i had this exam in university which was to create book class which would have author, title, content and translator.
main requirement was to create only 1 class and create inner classes within it (author and translator)
and one Main class to test it.
Problem was that when i created author and translator objects and tried to change their names, both of them would change names.
Here's my code:
Book Class:
public class Book {
private Author author;
private Translator translator;
private String title;
private String text;
public interface IPerson {
public void setFirstName(String name);
public String getFirstName();
public void setLastName(String name);
public String getLastName();
}
//Author
public class Author implements IPerson{
private String firstName;
private String lastName;
public Author(String f, String l){
firstName = f;
lastName = l;
author = this;
}
public void setFirstName(String name){
this.firstName = name;
}
public String getFirstName(){
return this.firstName;
}
public void setLastName(String name){
this.lastName = name;
}
public String getLastName(){
return this.lastName;
}
}
public Author getAuthor(){
return this.author;
}
//Translator
public class Translator extends Author{
public Translator(String f, String l) {
super(f, l);
translator = this;
}
}
public Translator getTranslator(){
return this.translator;
}
public String getTranslatorFullName(){
return this.getTranslator().getFirstName() + " " + this.getTranslator().getLastName();
}
public String getText() {
return this.text;
}
public void setText(String text) {
this.text = text;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDisplayTitle(){
return getTitle() + " Author: " + this.getAuthor().getFirstName() + " " + this.getAuthor().getLastName();
}
}
Main Class:
public class Main {
public static void main(String[] args){
Book mybook = new Book();
mybook.setTitle("Fight Club");
mybook.setText("First rule of Fight Club, you do not talk about Fight Club");
Book.Author author = mybook.new Author("John","Doe");
Book.Translator translator = mybook.new Translator("Alan","Rickman");
System.out.println(mybook.getDisplayTitle());
System.out.println(mybook.getAuthor().getLastName());
System.out.println(mybook.getAuthor().getFirstName());
System.out.println(mybook.getTranslatorFullName());
System.out.println(mybook.getTranslator().getFirstName());
}
}
It Had to pass these tests, what was my problem?
Don't tell me to make Translator implement IPerson, it was my teachers request to extend
You can fix it like this:
public Author(String f, String l, boolean authorCheck){
firstName = f;
lastName = l;
if(authorCheck)
{
author = this;
}
}
public Author(String f, String l){
firstName = f;
lastName = l;
author = this;
}
public Translator(String f, String l) {
super(f, l, false);
translator = this;
}
It would make more sense if Translator implements IPerson instead of extending Author.
You're making a super(f,l) call in the constructor of Translator. Translator is changing the Author fields as the superclass of Translator is Author.

Song Class, Using abstract class and interface

What I'am trying to do with this program is output the information of a song using the toString on Song class. When I output it, everything is fine except the SongType/genre. It is still outputting UNDETERMINED.
abstract class Song implements ISong //SONG CLASS
{
private String name;
private String rating;
private int id;
private SongType genre;
public Song()
{
name = " ";
rating = " ";
id = 0;
genre = SongType.UNDETERMINED;
}
public Song(String name, String rating, int id)
{
this.name = name;
this.rating = rating;
this.id = id;
this.genre =Song.UNDETERMINED;
}
public void setName(String name)
{
this.name = name;
}
public void setRating(String rating)
{
this.rating = rating;
}
public void setID(int id)
{
this.id = id;
}
public String getName()
{
return(this.name);
}
public String getRating()
{
return(this.rating);
}
public int getID()
{
return(this.id);
}
#Override
public String toString()
{
return("Song: " + this.name +
"\nID: " + this.id +
"\nRating: " + this.rating +
"\nGenre: " + this.genre);
}
}
class Pop extends Song //POP CLASS
{
public Pop(String name, String rating, int id)
{
super(name, rating, id);
}
}
interface ISong //INTERFACE
{
public enum SongType {POP, COUNTRY, HIPHOP, SOUL, UNDETERMINED;}
}
public class test{
public static void main(String [] args)
{
Song one = new Pop("Pop Song", "Five", 123);
System.out.println(one);
}
}
When I output it, everything is fine except the SongType/genre. It is still outputting UNDETERMINED.
But where do you actually set your genre field to anything but SongType.UNDETERMINED?
I suggest that you give the Song class and ISong interface a public SongType getGenre() method that returns the current genre, as well as an appropriate setter method, public void setGenre(SongType genre) and constructors that accept a SongType genre parameter if need be. The toString() method should call the getGenre() method to get the current genre state.
Most important, you will need to set the genre in a concrete class to something other than SongType.UNDETERMINED before trying to print it out.

Categories

Resources