Joetjah
Joetjah

Reputation: 6132

How to create an instance of an extended class?

I have a class named Item. It has the following parameters: User owner, Category category and String description.

Next to that, I have a subclass named Painting which extends the Item-class. A Painting has two parameters: title and painter.

At some point in the code, I'd like to create a Painting object. It should be possible to run code from a test file that goes like this:

User u1 = new User ("[email protected]");
Category cat = new Category("cat2");
Item painting = sellerMgr.offerPainting(u1, cat, "Selfportret", "Rembrandt");

There should be code in the class sellerMgr which should be able to register (create) that item (as a Painting), so I can use it in a database for example. How do I call that code exactly? I get confused whenever or not to create a new Item or a new Painting, and which parameters to add in the creation code.

Upvotes: 0

Views: 11699

Answers (4)

Zylth
Zylth

Reputation: 217

You have a new class

public class Painting extends Item

you'll want a constructor that provides two new parameters, String title, User painter

public Painting(User owner, Category category, String description, String title, User painter){
    super(owner, category, description);
    this.title = title;
    this.painter = painter
}

Whenever you want a new instance of a Painter you can call this method that will set up any of the Item variables for you, while introducing the two new parameters you desire. A call could look like either

Item paintingAsItem = new Painting(u1, cat, "desc", "Selfportret", "Rembrandt"); //Generic
Painting painting = new Paining(u1, cat, "desc", "Selfportret", "Rembrandt");

Upvotes: 3

Andres Olarte
Andres Olarte

Reputation: 4380

In this case sellerMgr.offerPainting should create and return an object of type Painting. Painting can be cast to an Item, but for the most part you should be using the extending class, which will have more functionality than Item.

Upvotes: 0

hmatar
hmatar

Reputation: 2419

Painting constructor should take Category and User as arguments and should pass them to super which calls the constructor of 'Item'.

Like:

public Painting(User user, Category category) { super(user, category); ...
}

Upvotes: 0

Dave L.
Dave L.

Reputation: 9781

Probably you want something like this:

Painting p = new Painting(u1, cat, title, painter);

Assuming your class definition is like this:

public class Painting extends Item {

  private String title;
  private String painter;

  public Painting(User owner, Category category, String title, String painter){
    super(owner, category);
    this.title = title;
    this.painter = painter;
  }
}

Upvotes: 1

Related Questions