将一个类的String存储到另一个类的对象中

时间:2017-09-02 20:16:20

标签: java oop tostring

我正在开发一个将图书链接到作者的项目。作者信息是图书类的一部分,它是图书类中的Author对象,其数据将成为图书类的一部分。我有作者类:

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;
     }
}

和书类:

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;
    }
}

我需要将toString()方法的内容存储在book类的Author变量中作为作者信息。我该怎么做?

1 个答案:

答案 0 :(得分:1)

您不需要存储Author类的toString()方法的值,这会不必要地耦合您的类,并打破优秀OO设计的核心原则之一。

Author类的toString方法应该负责呈现其状态的合理字符串表示(它似乎)。你的书类也应该这样做,委托与它交互的类来做同样的事情:

public String toString() {
   return "Book is " + name + "Author and author info "+ author.toString() + "Price " + price + "Quantity " + quantity;
}

正如评论中所述,您已经在问题中发布的代码段中执行此操作,您的问题暗示这可能不是“按设计”。我建议研究对象封装和委托。