如何在Java中创建和使用来自其他类的对象

时间:2016-05-26 09:52:52

标签: java class object

我不知道如何在其他类中创建和使用其他类中的对象。例如,我希望从另一个类(Item)

创建Publisher
public class Item {
    private String title;
    private String publisher;
    private int price,year,quantity;

    Item(String title,String publisher,int price,int year,int quantity){
        //Constructor goes here 
    }
}

//this is the publisher class:

public class Publisher {

    private String name,address,country,city;

    Publisher(String name,String address,String country,String city){
        this.setName(name);
        this.setAddress(address);
        this.setCountry(country);
        this.setCity(city);
    }
}

2 个答案:

答案 0 :(得分:1)

你尝试了什么?这很简单:

public class Item {
    ....
    void Test() {
        Publsiher p = new Publisher("a","b","c","d");
        //do some things
    }
}

答案 1 :(得分:0)

public class Item{
    public Item(){
        Publisher p = new Publisher('Name','Address','Country','City');
    }
}

在构造函数Item()中创建一个新的Publisher对象“p”,其中包含您选择的输入值('name','address,'country','city')。