Reputation: 53
Hi guys trying to access the super class from a subclass and I have to add a instance of to the ArrayList, I am trying to sort the super class instance but I wont let me do this.
public class Basket extends ArrayList<Product> implements Serializable
{
private static final long serialVersionUID = 1;
private int theOrderNum = 0; // Order number
/**
* Constructor for a basket which is
* used to represent a customer order/ wish list
*/
public Basket()
{
theOrderNum = 0;
}
}
The subclass I am using is below, I have tried the collections.sort shown below underneath the super.add but for some reason it will not let me access the super class, here is what I have tried.
public class BetterBasket extends Basket implements Serializable
{
private static final long serialVersionUID = 1L;
@Override
public boolean add( Product pr ) // Add a product to the
{
super.add(pr);
Collections.sort(super, super.get(0).getProductNum());
}
}
I am trying to sort it by the product number stored in the super class, shown in the first example.
Upvotes: 0
Views: 477
Reputation: 72874
You can simply refer to this
object since it already extends ArrayList
and holds the elements that you added using super.add(pr)
and that you want to sort:
Collections.sort(this, ....
The second parameter should be a Comparator
implementation, and not the first element in the list.
Collections.sort(this, new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
return p1.getProductNum() - p2.getProductNum();
}
});
Upvotes: 3
Reputation: 34628
The Collection.sort()
method expects either a collection of objects that implement Comparable, or a collection of objects and a Comparator object that allows comparing them.
So you can't just pass it an integer as the second parameter.
You need to read up on the Comparator
and build a Comparator
that knows how to compare two Product
objects, or write Product
so that it implements Comparable
.
One other thing is that you cannot access a private
member of your superclass from a subclass. This is a very basic concept in Object Oriented Programming. You can only access its protected, public, or package-accessible fields.
If you do have visible (protected/public/package-accessible) field, you don't need to use the super
keyword to access it, because the idea of extending a class is that you inherit its behavior and its state, so if a field is visible, you can just access it by its name or this
.name.
You need to use the super
keyword only if you need to access methods that you have overridden in your subclass, or fields that you have hidden (which you shouldn't do anyway).
Upvotes: 2