Abstract classes and Interfaces

0

I have to make a class hierarchy in which I have

1 - Product

1.1 - Book has Digital Book - Physical Book

1.2 - Clothing has Pantalon - Shirt

I am asked to implement the interface Comparable to compare books for its isbn (attribute of class BOOK), my question is ... Where is the interface implemented and where is the compareTo method implemented? In the Book class or in the Daughters Digital Book and Physical Book?

In other words, do this:

public abstract class Libro extends Producto implements Comparable

What causes you to implement the compareTo method in the Daughters. That will have the same code in both.

Can I make only Book have the compareTo method? What parameter should the method receive?

public int compareTo(Object o)
public int compareTo(Libro o)

@Override
public int compareTo(Object o) {
    this.isbn.compareTo(((Libro) o).getisbn)
}

The API talks about Object although I suppose that as an example and it is allowed to change for any object you are working with ... Or you must pass Object and do the corresponding cast.

    
asked by Tygreton 15.04.2018 в 19:42
source

1 answer

1
  

Can I make only Book have the compareTo method? What parameter should the method receive?

Yes, and you are doing well. But instead of implementing Comparable implement Comparable<Libro> :

public abstract class Libro
    extends Producto
    implements Comparable<Libro>

And so you save the cast in:

@Override
public int compareTo(Libro o) {
    this.isbn.compareTo(o.isbn);
}
    
answered by 15.04.2018 в 19:50